Given an array with n elements, I want to calculate the largest range of the array in which there are just as many odd as even numbers.
Example
Input:
2 4 1 6 3 0 8 10 4 1 1 4 5 3 6
Expected output:
12
What I tried
I tried using the following steps:
- change all odd numbers to 1 and all even numbers to -1
- Inspect all possible sub-arrays, and for each calculate the sum of the 1 and -1 values.
- Take the largest of these sub-arrays that has a sum of 0
But this has a time complexity of O(n^2).
Question
How can I do this in O(n)?
This is a common dynamic programming problem. We can maintain suboptimal solutions by iterating through the list and at the same time updating optimal solution. It is similar to finding a maximum element of array. Set the first element as maximum and update it in each iteration if it is needed. This problem just needs a bit more.
We need 5 pointers (integers, and actually 5). Start pointer, end pointer and current pointer, maxend, maxstart. Set the
start
andcurrent
pointer to the start of the array. While the next coming elements obey the rules (alternating odd and even), increase thecurrent
pointer. Once they don't obey the rule, set the end pointer to the current pointer. Compare the difference ofend-start
pointer, if it is bigger than maxend-maxstart then change the maxend and maxstart and continue this operation. At the end you can print the part of array between maxstart and maxend.