#C4081. Longest Balanced Subarray
Longest Balanced Subarray
Longest Balanced Subarray
Given an array of integers containing only 0s and 1s, your task is to find the length of the longest contiguous subarray that has an equal number of 0s and 1s.
The approach typically involves converting 0s to -1s and then using a prefix sum technique. If at later index j the prefix sum equals the prefix sum at an earlier index i, then the subarray from index i+1 to j has a sum of zero, meaning it has an equal number of -1s (0s) and 1s. In mathematical notation, if prefix[j] = prefix[i]
, then the length of the subarray is given by \( length = j - i \).
Try to design an algorithm with O(n) time complexity.
inputFormat
The first line contains an integer n (0 ≤ n ≤ 105), representing 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.
## sample2
0 1
2
</p>