#C11823. Longest Balanced Subarray

    ID: 41182 Type: Default 1000ms 256MiB

Longest Balanced Subarray

Longest Balanced Subarray

You are given an array of integers where each integer is one of 0, 1, or 2. A balanced subarray is defined as a contiguous segment of the array in which the number of 0s, 1s, and 2s are equal. Formally, for a subarray S, let \( c_0, c_1, c_2 \) be the counts of 0, 1, and 2 respectively. The subarray is balanced if \( c_0 = c_1 = c_2 \).

Your task is to determine the length of the longest balanced subarray. If no such subarray exists, output 0.

The problem requires implementing an efficient solution to handle multiple test cases. Consider using prefix sums and a hash mapping of differences among counts to achieve an optimal solution.

inputFormat

The first line of input contains an integer T representing the number of test cases.

For each test case, the first line contains an integer n — the size of the array. The second line contains n space-separated integers that are either 0, 1, or 2.

outputFormat

For each test case, output a single integer — the length of the longest balanced subarray.

## sample
3
6
0 1 2 0 1 2
7
0 1 1 2 0 2 1
5
0 0 1 1 2
6

6 0

</p>