Problem · Array
Longest Prefix-Valid Binary Subarray
Learn this problemProblem statement
You are given a binary array arr containing only 0s and 1s.
A contiguous subarray is prefix-valid when every non-empty prefix of that subarray contains at least as many 1s as 0s.
Return the length of the longest prefix-valid contiguous subarray. If no non-empty prefix-valid subarray exists, return 0.
Function
longestPrefixValidBinarySubarray(arr: int[]) → intExamples
Example 1
arr = [1,0,1,0,0]return = 4The subarray [1,0,1,0] is prefix-valid: its prefix balances of 1s minus 0s are 1, 0, 1, 0. Extending it by the final 0 makes the balance negative.
Example 2
arr = [0,1,1,0]return = 3The longest valid choice starts at index 1: [1,1,0] has prefix balances 1, 2, 1.
Example 3
arr = [0,0,0]return = 0Every non-empty subarray starts with 0, so its first prefix already has more 0s than 1s.
Constraints
1 <= arr.length <= 100000arr[i]is either0or1