#K70582. Maximal Subarray with Equal Even and Odd Numbers
Maximal Subarray with Equal Even and Odd Numbers
Maximal Subarray with Equal Even and Odd Numbers
You are given an array of n integers. Your task is to find the length of the longest contiguous subarray that contains an equal number of even and odd integers.
To solve this problem, you can transform the array values into a balance: add +1 for every even number and -1 for every odd number. Then, find the longest subarray whose cumulative sum is zero. The answer will be the length of that subarray.
The formula for the balance is given by:
\( \text{balance}_i = \sum_{j=0}^{i} (a_j\ is\ even? +1 : -1) \)
where a subarray \( [i, j] \) has equal numbers of even and odd integers if \( \text{balance}_j - \text{balance}_{i-1} = 0 \).
inputFormat
The first line contains a single integer n representing the number of elements in the array.
The second line contains n space-separated integers, the elements of the array.
outputFormat
Output a single integer representing the maximum length of a contiguous subarray with an equal number of even and odd numbers.
## sample7
1 2 3 4 5 6 7
6