AceYourInterviews
Checking sign-in…

28. Longest Ones with at Most K Flips

IntermediateExact zero-budget variable window

Choose a continuous part of the binary array and change at most k of its zero positions to ones. Return the largest length of a part that can thereby become all ones.

Count the actual number of zero positions that need changing. You do not have to modify the array permanently or use every available flip.

Example 1

Input

nums=[1,1,0,0,1,1,1,0], k=1

Output

4

Explanation: Indices 3..6 contain one zero and three ones, so one flip yields length four.

Example 2

Input

nums=[0,0,0], k=1

Output

1

Explanation: Only one zero can be included in a feasible all-ones result.

Constraints

  • 0 <= nums.length <= 105
  • nums[i] is 0 or 1
  • 0 <= k <= 231 - 1
Hints
Hint 1

What exact count determines the flips needed for one binary window?

Hint 2

Which outgoing values actually free budget?

Hint 3

Track zeros, shrink while over budget, then maximize the valid length.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Remove ones until an outgoing zero frees budget

[1,1,0,0,1,1,1,0]
1
4