#C4922. Longest Subarray with Equal Number of Ones and Zeros

    ID: 48514 Type: Default 1000ms 256MiB

Longest Subarray with Equal Number of Ones and Zeros

Longest Subarray with Equal Number of Ones and Zeros

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

To solve this problem efficiently, consider mapping each 0 to -1 and each 1 to +1. Let the prefix sum at index \(i\) be denoted by \(count_i\). The challenge is to find two indices \(i\) and \(j\) such that \(count_i = count_j\), which implies that the subarray between \(i+1\) and \(j\) has an equal number of 0's and 1's. The length of this subarray is \(j - i\), and your goal is to maximize this length.

inputFormat

The first line contains an integer \(T\), representing the number of test cases. Each of the following \(T\) lines contains a space-separated list of binary integers (either 0 or 1) representing the array.

outputFormat

For each test case, output a single integer on a new line: the length of the longest contiguous subarray with an equal number of 0's and 1's.

## sample
3
1 0 1 1 0 1
1 1 1 1
0 0 1 1 0 1 0
4

0 6

</p>