588/670

588. Max Consecutive Ones III

Medium

You are given a binary array nums (every entry is 0 or 1) and an integer k. You are allowed to pick at most k zeros and flip them into ones.

Your function receives the array nums and the integer k, and must return a single integer: the length of the longest contiguous run of ones you can produce with those flips.

Put differently: what is the longest window of the array that contains at most k zeros?

Example 1:

Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2

Output: 6

Explanation: Flip the zeros at indices 5 and 10. The stretch nums[5..10] then reads 1 1 1 1 1 1 — six ones in a row, and no choice of two flips does better.

Example 2:

Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3

Output: 10

Explanation: Flipping the zeros at indices 4, 5 and 9 joins nums[2..11] into a block of ten ones.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • nums[i] is 0 or 1
  • 0 ≤ k ≤ nums.length

Hints:

Flipping is a story. Reword the task without it: find the longest contiguous window that contains at most k zeros.

Slide a window: move the right edge one step at a time and count the zeros inside. Whenever the count exceeds k, advance the left edge until it drops back to k. The best window length ever seen is the answer.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2

Expected output: 6