Max Consecutive Ones III

medium

You are given a binary array nums (each element is 0 or 1) and an integer k. You may flip at most k zeros to ones.

Return the length of the longest contiguous run of 1s you can produce.

Hints

Flipping zeros to get a run of ones — what does that run look like as a window?
It's a window containing at most k zeros (all of which you flip).
Grow the window on the right, and shrink from the left whenever it holds more than k zeros.

Common doubts

A window with at most k zeros is achievable by flipping exactly those zeros, so its length is a valid candidate. You only need to count zeros, not perform flips.
The window's feasibility depends solely on how many zeros it contains; the ones are free. The count rises on an entering zero and falls on a departing one.
Then every zero can be flipped and the answer is the whole array length — the window never becomes invalid.

Interview follow-ups

Symmetric — it becomes the longest window with at most k ones; swap which value you count.
A common variant never shrinks the window's size below the current best — it only slides — giving the same answer with one comparison removed.

Fun facts

  • This is the binary special case of 'longest window with at most k of some bad element' — the same window works for any single forbidden symbol.
  • The never-shrink variant treats the window like a monotone frontier, a trick reused in streaming max-window computations.

Asked at

AmazonGoogleMicrosoftMeta
Frequently Sometimes Occasionally
Example 1
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Flip the two zeros at indices 5 and 10... the best window [1,1,1,1,0,0]->flip gives a run of 6.
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
Flipping three well-chosen zeros yields a run of 10 ones.
Constraints

- 1 <= nums.length <= 10^5 - nums[i] is either 0 or 1. - 0 <= k <= nums.length

Solve this problem →