299. Equal Zeros and Ones
Given an array of only 0s and 1s, print the length of the longest contiguous stretch containing exactly as many 0s as 1s. If there is none, print 0.
The trick is a change of view. Treat every 0 as -1 and every 1 as +1.
Then a stretch has equal counts exactly when it sums to zero, and a stretch
sums to zero exactly when the running total is the SAME at both of its ends.
So keep a map from running total to the FIRST index where it occurred. Meeting that total again means the stretch in between is balanced, and the earliest occurrence gives the longest such stretch.
Constraints - `1 ≤ n ≤ 200000` - `each a[i] is 0 or 1`
Input
The first line contains an integer n.
The second line contains n values, each 0 or 1.
Output
Print one integer, the length of the longest balanced stretch, or 0 if there is none.
Hints
Four rungs, in order. The last two open once you have submitted an attempt. A wrong one counts.