Problem 817
Contiguous Array
Medium · 20 pts · Array, Hash Table, Prefix Sum
Problem
In a binary array, find the length of the longest block of consecutive elements that contains the same number of 0s and 1s, or 0 if there is none. Count a 1 as +1 and a 0 as -1; a block is balanced exactly when its sum is 0, which means the running sum has the same value at both of its ends. Store the first position of every running sum in a hash map.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1]. Every value is 0 or 1.
Output
Print the length of the longest balanced subarray.
Constraints
1 <= N <= 100000; A[i] is 0 or 1
Example input
3 0 1 0
Example output
2
Explanation
In 0 1 0, the blocks 0 1 and 1 0 each have one 0 and one 1, so they are balanced with length 2. The whole array has two 0s, so the answer is 2.