#K94347. Longest Subarray with Equal Odd and Even Numbers

    ID: 38621 Type: Default 1000ms 256MiB

Longest Subarray with Equal Odd and Even Numbers

Longest Subarray with Equal Odd and Even Numbers

Nadia is given an array of n positive integers. She is interested in finding the longest contiguous subarray that contains an equal number of odd and even elements. In other words, you need to find the longest segment of the array for which the count of odd numbers equals the count of even numbers.

Let the array be denoted as \(A = [a_1, a_2, \dots, a_n]\). Define a function f(i) such that for an index i, if \(a_i\) is even, add +1; if \(a_i\) is odd, add -1. The problem reduces to finding indices \(i\) and \(j\) (with \(i < j\)) such that:

[ \sum_{k=i+1}^{j} f(k) = 0, ]

which implies that the number of evens equals the number of odds in the subarray from index \(i+1\) to \(j\). Your task is to compute the maximum length of such a subarray. If no valid subarray exists, output 0.

inputFormat

The first line of input contains an integer n representing the number of elements in the array.
The second line contains n space-separated positive integers denoting the array elements.

Example:

6
1 2 3 4 5 6

outputFormat

Output a single integer representing the length of the longest contiguous subarray with an equal number of odd and even elements.

Example:

6
## sample
6
1 2 3 4 5 6
6