#K35857. Longest Balanced Subarray
Longest Balanced Subarray
Longest Balanced Subarray
Given an array of binary numbers (0s and 1s), your task is to find the length of the longest contiguous subarray that contains an equal number of 0s and 1s. To solve this problem, you can treat 0 as -1 and 1 as 1, and then the problem reduces to finding a subarray whose sum is zero.
Formally, let the array be \(a_1, a_2, \ldots, a_n\). We need to find indices \(l\) and \(r\) such that \[ \sum_{i=l}^{r} \Big(\mathbf{1}_{\{a_i=1\}} - \mathbf{1}_{\{a_i=0\}}\Big) = 0 \] and maximize \(r - l + 1\). If no such subarray exists, output 0.
For example, if the input array is [0, 1]
, the entire array is balanced and its length is 2.
inputFormat
The first line contains an integer (n) ((1 \leq n \leq 10^5)), which represents the number of elements in the array. The second line contains (n) space-separated integers, each being 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. If there is no such subarray, output 0.## sample
2
0 1
2