#C5721. Longest Contiguous Subarray with Equal Number of 0s and 1s

    ID: 49402 Type: Default 1000ms 256MiB

Longest Contiguous Subarray with Equal Number of 0s and 1s

Longest Contiguous Subarray with Equal Number of 0s and 1s

Given a binary array, your task is to find the length of the longest contiguous subarray that contains an equal number of 0s and 1s.

The key insight is to transform the array by converting every 0 into -1. Consequently, finding a subarray with an equal count of 0s and 1s is equivalent to finding a subarray whose sum is 0. Formally, if we define \(x_i\) as follows:

\( x_i = \begin{cases} -1, & \text{if the element is } 0 \\ 1, & \text{if the element is } 1 \end{cases}\)

then we need to find the maximum length \(L\) such that for some index \(j\):

\[ \sum_{i=j}^{j+L-1} x_i = 0 \]

Implement an efficient solution to handle large arrays.

inputFormat

The input consists of two lines. The first line contains an integer \(n\) which denotes the number of elements in the array. The second line contains \(n\) space-separated integers, each either 0 or 1.

outputFormat

Output a single integer representing the length of the longest contiguous subarray with an equal number of 0s and 1s.

## sample
7
0 1 0 0 1 1 0
6