Skip to content
Problem 1004 · LeetCode 1004(opens in a new tab)

Max Consecutive Ones III

MediumArrays

You get an array nums made of 0s and 1s, and a number k. You may turn up to k of the 0s into 1s.

Return the length of the longest stretch of back-to-back 1s you can end up with.

Example 1

Input:  nums = [1, 0, 0, 1, 1, 0, 1], k = 1
Output: 4
Why:    flip the 0 at index 5 to get 1, 1, 1, 1 at indexes 3 to 6
2 more examples and the constraints

Example 2

Input:  nums = [0, 0, 0], k = 0
Output: 0
Why:    there are no 1s and no flips

Example 3

Input:  nums = [1, 0, 1, 0, 1], k = 2
Output: 5
Why:    both 0s can be flipped, so the whole array works

Constraints

  • 1 ≤ nums.length ≤ 100,000
  • Each nums[i] is 0 or 1
  • 0 ≤ k ≤ nums.length

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every startO(n²)
  2. Sliding windowO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeCell reads for 100,000 numbersVerdict
Try every startO(n²)
Too slow; billions of reads
Sliding windowO(n)
Best; each index in and out once

n = length of nums.

Edge cases to test

  • k = 0. No flips: the answer is the longest run of 1s already there, which may be 0.
  • All zeros. [0, 0, 0, 0, 0] with k = 3 gives 3: a window can hold three flipped zeros.
  • k at least the number of zeros. Every zero can be flipped, so the answer is the whole length.
  • Best window at the end. Update best after every move of right, not only when the window shrinks, or a run that reaches the last index is missed.

Common mistakes

  • Actually flipping 0s in the array and trying to undo them, instead of just counting zeros in the window.
  • Shrinking with if but then recording the length before the window is valid again.
  • Decreasing zeros when the cell leaving on the left is a 1.

How to talk through it

  1. 1Clarify. Is k at most the length? Can the answer be 0 when there are no 1s and k is 0?
  2. 2Reframe. Flipping is a distraction: find the longest window with at most k zeros.
  3. 3Brute force first. Every start with an inner scan is O(n²); say why it repeats work.
  4. 4Slide the window. Grow right, count zeros, shrink left while over k. Both pointers only move forward, so O(n).
  5. 5Test out loud. Run k = 0, an array of only zeros, and a case where the best run ends at the last index.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?