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)?
Given: array a
Task: find the largest sub-array with an even amount of odd and even nubers
Solution O(n)
create a hash map m with the highest entry for each cumulative sum when replacing odd numbers with -1 and even numbers with 1, in java:
find the largest sub-array which sums up to 0 by looking for the biggest distance using m, in java:
It's based on the observation that you can get the sum (after transforming the elements to 1 and -1) from x to y with cumSum[y] - cumSum[x - 1]. So if we want this to be 0 then they need to be the same (careful if x = 0 then cumSum = 0, cumSum[-1] is not defined).