#C9180. Largest Subarray with Equal Number of 0s and 1s
Largest Subarray with Equal Number of 0s and 1s
Largest Subarray with Equal Number of 0s and 1s
Given a binary array of size (n), find the length of the largest contiguous subarray that contains an equal number of 0s and 1s. This problem can be efficiently solved using the prefix sum technique. Treat each 0 in the array as -1 and each 1 as +1. Then, if the prefix sum at two different indices is the same, the subarray bounded by these indices has an equal number of 0s and 1s. Formally, let ( a[i] = \begin{cases} -1, & \text{if } a[i] = 0 \ 1, & \text{if } a[i] = 1 \end{cases} ) and define ( S(i) = \sum_{j=0}^{i} a[j] ). If ( S(i) = S(j) ) for ( i < j ), then the subarray ( [i+1, j] ) has an equal number of 0s and 1s. Your task is to compute the maximum length of such a subarray.
inputFormat
The first line contains a single integer (n) (the number of elements in the binary array). The second line contains (n) space-separated integers where each integer is either 0 or 1.
outputFormat
Output a single integer representing the length of the largest subarray that has an equal number of 0s and 1s.## sample
7
1 0 0 1 0 1 1
6