Max Consecutive Ones III (LeetCode 1004): Solution and Explanation

Medium
Array
Binary Search
Sliding Window
Prefix Sum

Given a binary array and a budget of k flips from 0 to 1, return the length of the longest run of ones you can make.

Intuition

You never need to decide which zeros to flip up front. Any stretch of the array that contains at most k zeros can be turned into all ones, so the question becomes: what is the longest subarray with at most k zeros?

Checking every subarray costs O(n^2). But if a window with too many zeros is invalid, any wider window around it is invalid too, so the left edge never needs to move back.

Grow the window one element at a time on the right. Each zero that enters spends one flip. When the window holds more than k zeros, move the left edge forward until a zero leaves and its flip comes back.

After that, the window is valid again and its length is a candidate for the answer. Both edges only move forward, so the whole scan is linear.

Approach: Sliding window with a zero counter

  1. Set left = 0, zeros = 0 and best = 0.
  2. For each right, if nums[right] is 0, add one to zeros.
  3. While zeros > k, check nums[left]: if it is 0, subtract one from zeros. Then move left one step right.
  4. The window [left, right] now holds at most k zeros. Set best = max(best, right - left + 1).
  5. Return best.

Step-by-step example

nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
  1. Indices 0 to 4 enter. The zeros at 3 and 4 use both flips, and the window [0, 4] has length 5, so best = 5.
  2. Index 5 is a third zero. zeros = 3 > 2, so left moves past the ones at 0, 1 and 2 and then past the zero at 3, ending at left = 4 with zeros = 2.
  3. Indices 6 to 9 are ones. The window grows to [4, 9], length 6, so best = 6.
  4. Index 10 is a zero. left moves past the zero at 4, giving [5, 10], length 6. The answer stays 6.

Code: Python, Java, C++

1class Solution:
2    def longestOnes(self, nums: List[int], k: int) -> int:
3        left = 0
4        zeros = 0
5        best = 0
6        for right in range(len(nums)):
7            if nums[right] == 0:
8                zeros += 1
9            while zeros > k:
10                if nums[left] == 0:
11                    zeros -= 1
12                left += 1
13            best = max(best, right - left + 1)
14        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

right visits each index once and left moves forward at most n times across the whole scan.

Space

O(1)

Only the two edges, the zero count and the best length are stored.

Other approaches

Non-shrinking window (time O(n), space O(1))

Replace the while with an if: when the window holds too many zeros, slide it by one instead of shrinking it. The window size never drops, so at the end right - left + 1 is the answer.

Prefix zero counts with binary search (time O(n log n), space O(n))

Build prefix counts of zeros, then for each right edge binary search the smallest left edge whose window holds at most k zeros.

Try every window (time O(n^2), space O(1))

For each start, extend right while the zero count stays within k. Easy to write but quadratic.

Common mistakes

  • Decrementing zeros for every element that leaves, instead of only for zeros.
  • Moving left before checking nums[left], which checks the wrong element.
  • Recording best before the shrinking loop finishes, when the window still holds too many zeros.
  • Forgetting the k = 0 case: the window must then contain only ones, and an all-zero array gives 0.

Frequently asked questions

Do I need to remember which zeros were flipped?

No. Every zero inside the window counts as flipped, so a single counter is enough.

How is this related to Max Consecutive Ones?

Max Consecutive Ones is the k = 0 case. This version adds a budget, which turns a simple run counter into a sliding window.

Why is the inner while loop still O(n) overall?

Each pass moves left forward by one, and left never goes back, so it moves at most n times in total.