#C12662. Longest Contiguous Subarray with Equal Number of 0s and 1s
Longest Contiguous Subarray with Equal Number of 0s and 1s
Longest Contiguous Subarray with Equal Number of 0s and 1s
Given an array of binary integers (0s and 1s), find the length of the longest contiguous subarray that contains an equal number of 0s and 1s.
One optimal approach is to transform every 0 into -1 and compute a running sum. When the same running sum appears twice, the subarray between these indices has an equal number of -1s and 1s (equivalently, 0s and 1s). Mathematically, if the array is \( A = [a_1, a_2, \dots, a_n] \) where \( a_i \in {0,1} \), and we define transformed values \( b_i = -1 \) if \( a_i = 0 \) and \( b_i = 1 \) if \( a_i = 1 \), then a subarray \( [b_i, \dots, b_j] \) sums to zero if and only if it contains an equal number of 0s and 1s.
inputFormat
The input is given via standard input in the following format:
- The first line contains a single integer \( n \), the number of elements in the array.
- The second line contains \( n \) space-separated integers (each either 0 or 1), representing the array.
outputFormat
Output a single integer via standard output: the length of the longest contiguous subarray with an equal number of 0s and 1s.
## sample7
0 0 1 0 1 1 0
6