To solve this problem, we need to find the maximum length of a contiguous subarray (subarray) where the sum of the elements is even. The approach involves leveraging the properties of prefix sums and their parity (even or odd).
Approach
Prefix Sum and Parity: The sum of a subarray from index i to j can be determined using prefix sums. If the parity (even or odd) of the prefix sum at two different indices is the same, the subarray between those indices has an even sum.
Tracking First Occurrence: We maintain a dictionary to record the first occurrence of each parity (even or odd) of the prefix sum. This helps in efficiently calculating the maximum length of subarrays with even sums.
Edge Case Handling: If the total sum of the array is even, the entire array is the longest valid subarray. Otherwise, we use the tracked first occurrences to determine the maximum length.
Solution Code
python
from typing import List
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
prefix_sum = 0
first_occurrence = {0: 0}
max_len = 0
for i in range(len(nums)):
prefix_sum += nums[i]
parity = prefix_sum % 2
if parity not in first_occurrence:
first_occurrence[parity] = i + 1
else:
current_len = (i + 1) - first_occurrence[parity]
if current_len > max_len:
max_len = current_len
total_sum = prefix_sum
if total_sum % 2 == 0:
return len(nums)
else:
return max_len
Explanation
Initialization: We start with a prefix sum of 0 (even) at index 0.
Iterate Through Array: For each element, update the prefix sum and determine its parity.
Update First Occurrence: Track the first occurrence of each parity to compute potential subarray lengths.
Check Total Sum: If the total sum is even, the entire array is valid. Otherwise, return the maximum length found using tracked parities.
This approach efficiently computes the result in linear time, O(n), where n is the length of the input array, making it optimal for large datasets.