medium

Max Consecutive Ones III

Find the longest run of 1s you can make by flipping a limited number of 0s.

1. Define the problem

Max Consecutive Ones III

Given a binary array and an integer k, return the longest run of 1s you can make by flipping at most k zeros . Treat zeros as a budget inside the window: grow right, and shrink left whenever the zero count exceeds k.

Constraints

  • 1 ≤ nums.length ≤ 105
  • numsi is either 0 or 1
  • 0 ≤ k ≤ nums.length

Example

Inputnums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 2
Output6

Explanation Flip the two 0s at indices 5 and 4 (or nearby) to get a run of six 1s.

2. Visualize the solution

Window may hold at most k zeros

Window may hold at most k zeros
Statusvalid

Two zeros so far; zeros = 2 <= k; best = 4.

What happens in this step

window = [0, 3]  [1, 1, 0, 0]

before: zeros = 0 (right = 1)
  right = 2: nums[2] = 0 → zeros = 1
  right = 3: nums[3] = 0 → zeros = 2

Both zeros fit inside the k = 2 flip budget — window valid; best becomes 4.
Step 1 of 4

Steps to visualize

  1. Grow right; if the new value is 0, increment the zero budget used.
  2. While zeros exceed k, advance left and decrement when leaving a zero.
  3. The window always represents a stretch fixable with at most k flips.
  4. Update best with the current window length after each adjustment.
  5. Continue until right reaches the end of the array.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Window may hold at most k zeros
Statusvalid

Two zeros so far; zeros = 2 <= k; best = 4.

What happens in this step

window = [0, 3]  [1, 1, 0, 0]

before: zeros = 0 (right = 1)
  right = 2: nums[2] = 0 → zeros = 1
  right = 3: nums[3] = 0 → zeros = 2

Both zeros fit inside the k = 2 flip budget — window valid; best becomes 4.
Step 1 of 4
4. Solution

Solution

solution.tsTypeScript
function longestOnes(nums, k) {
  let left = 0;
  let zeros = 0;
  let best = 0;

  for (let right = 0; right < nums.length; right++) {
    if (nums[right] === 0) zeros++;

    while (zeros > k) {
      if (nums[left] === 0) zeros--;
      left++;
    }

    best = Math.max(best, right - left + 1);
  }

  return best;
}
Time
O(n)
Space
O(1)
5. Test cases

Test cases

InputExpectedCovers
nums = [1,1,1,0,0,0,1,1,1,1,0], k = 26Docstring example
nums = [1], k = 01Single one
nums = [0, 0, 1, 1], k = 24k covers all zeroes
nums = [1, 1, 1, 1], k = 04All ones
nums = [0, 0, 0], k = 11All zeroes with k = 1
nums = [1, 0, 1, 1, 0, 1], k = 02k = 0 is plain max consecutive ones
nums = [1,1,0,0,1,1,1,0,1,1], k = 27Walkthrough array best length 7