Example 1
- Input
- nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
- Output
- 6
Flip the zeros at indices 4 and 5 to get [1,1,1,0,1,1,1,1,1,1,0], whose longest run of ones has length 6.
Given a binary array nums and an integer k, you may flip at most k zeros to ones. Return the length of the longest contiguous subarray that contains only ones after the flips.
Given a binary array nums and an integer k, return the maximum number of consecutive 1s in the array if you can flip at most k 0s.
Flipping turns zeros into ones, so the task equals finding the longest contiguous subarray holding at most k zeros. For nums = [1,1,1,0,0,0,1,1,1,1,0] with k = 2 the answer is 6.
1 <= nums.length <= 10^5nums[i] is either 0 or 1.0 <= k <= nums.lengthFlip the zeros at indices 4 and 5 to get [1,1,1,0,1,1,1,1,1,1,0], whose longest run of ones has length 6.
Flip the zeros at indices 4, 5 and 9 to get a run of 10 consecutive ones.
No flips are allowed. The longest existing run is the two ones at indices 2 and 3.
Every nonempty interval contains a zero and no flip is available, so no run of ones exists.
Any two adjacent zeros can be flipped. Length 3 would need three flips, exceeding the budget.
Either zero can be flipped to produce a run of length 3. Tied optimal windows are allowed; only the length is returned.
Flipping at most k zeros means a candidate interval is usable exactly when it contains at most k zeros; ones cost nothing. In Example 1, indices 4 through 9 contain two zeros and four ones, giving length 6 after two flips. Track a window with a zero count. Extend its right edge, then remove values from its left until the zero budget is restored, keeping the longest valid length.
Reveal Brute Force: intuition, complexity, and code
k zeros.0 enters.k, move the left edge forward until the count is back within budget, dropping a zero from the count each time one leaves.k = 0: no flip is allowed, so the answer is the longest existing run of ones.k covers every zero, such as all zeros with k equal to the length: the whole array becomes ones and the answer is its length.0 leaves through the left edge, which freezes the window too small for the rest of the scan.left to right on a violation instead of sliding it forward, which skips valid windows in between.>= k as the shrink test instead of > k, which treats a window spending exactly the budget as invalid.For the longest subarray under a counted budget, keep the count as running window state and shrink from the left only while the budget is exceeded.