#K70342. Find Maximum Length of Contiguous Subarray with Equal Number of 0s and 1s
Find Maximum Length of Contiguous Subarray with Equal Number of 0s and 1s
Find Maximum Length of Contiguous Subarray with Equal Number of 0s and 1s
You are given a binary array consisting of 0s and 1s. Your task is to determine the maximum length of a contiguous subarray that contains an equal number of 0s and 1s.
The problem can be solved efficiently using a prefix sum technique. Replace every 0 with -1 and compute the running sum. If the same prefix sum appears at two different indices, it means that the subarray between these indices has equal numbers of 0s and 1s.
This problem is a classic example that requires careful handling of edge cases and efficient use of data structures.
inputFormat
The input is read from stdin and consists of:
- The first line contains an integer
n
(1 ≤ n ≤ 105), representing the number of elements in the array. - The second line contains
n
space-separated integers, each of which is either 0 or 1.
outputFormat
Output a single integer to stdout: the maximum length of a contiguous subarray with an equal number of 0s and 1s.
## sample2
0 1
2
</p>