Problem
Longest Balanced Binary Subarray
Learn this problemProblem statement
You are given an integer array arr containing only 0s and 1s.
Return the length of the longest contiguous subarray that satisfies both conditions:
- The subarray contains the same number of
0s and1s. - For every prefix of the subarray, the number of
1s is greater than or equal to the number of0s.
Function
longestBalancedBinarySubarray(arr: int[]) → intExamples
Example 1
arr = [1, 0, 1, 1, 0, 0, 1]return = 6The subarray [1,0,1,1,0,0] is balanced and every prefix has at least as many 1s as 0s.
Example 2
arr = [0, 1, 1, 0]return = 2The longest valid subarray is [1,0]. The full array is balanced, but its first prefix starts with more 0s than 1s.
Example 3
arr = [1,0,1,1,0,0,1]return = 6The subarray [1,0,1,1,0,0] is balanced, and every prefix has at least as many 1s as 0s.
Example 4
arr = [0,1,1,0]return = 2The full array is balanced, but its first prefix has more 0s than 1s. The longest valid subarray is [1,0].
Constraints
1 <= arr.length <= 2 * 10^5arr[i]is either0or1.