Max Consecutive Ones III

Medium

Topics
ArraySliding Window

Given a binary array nums and an integer target (the number of 0s you may flip to 1), return the maximum number of consecutive 1s achievable.

Example 1

10111203040516171819010length 6
The braced window is the longest run containing no more zeros than you are allowed to flip — length 6. Nothing is actually flipped; the window just tracks how many zeros it holds and shrinks when that exceeds the budget.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,1,1,0,0,0,1,1,1,1,0], target = 2
Output: 6

Example 2

00011213040516171809110111012013014115116117118length 10
Input:  nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], target = 3
Output: 10

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is 0 or 1
  • 0 <= target <= nums.length
Editorial — intuition, approach, complexity and pitfalls

Intuition

Do not think about which zeros to flip. Reframe the question: the answer is the length of the longest window that contains at most target zeros. The flipping is a story told around that invariant — nothing is ever actually flipped.

Once stated that way it is the canonical variable-size sliding window. Extend the right edge unconditionally; pull the left edge in only while the invariant is violated. Every index enters the window once and leaves at most once, which is where the linear bound comes from.

Approach

  1. Advance r one step and, if nums[r] is a zero, increment the zero count.
  2. While the count exceeds target, advance l, decrementing the count only when the cell being left behind is a zero.
  3. Record r - l + 1 as a candidate answer.

Dry Run

nums = [1,1,1,0,0,0,1,1,1,1,0]   target = 2

  r  nums[r]  zeros  window   len  best
  0     1       0    [0,0]     1    1
  1     1       0    [0,1]     2    2
  2     1       0    [0,2]     3    3
  3     0       1    [0,3]     4    4
  4     0       2    [0,4]     5    5
  5     0       2    [4,5]     2    5   <- third zero arrives, left edge jumps past two cells
  6     1       2    [4,6]     3    5
  7     1       2    [4,7]     4    5
  8     1       2    [4,8]     5    5
  9     1       2    [4,9]     6    6
 10     0       2    [5,10]    6    6

answer 6

At r = 5 the budget is blown, so the left edge moves from 0 to 4 — past the two zeros at indices 3 and 4 — restoring the invariant in one shrink.

Complexity

  • Time — O(n): r makes n moves and l makes at most n, so at most 2n pointer steps in total. Each element is examined a constant number of times.
  • Space — O(1): three integers. Nothing proportional to the input is stored.

Common Pitfalls

  • Trying to decide which zeros to flip, usually by sorting or by a greedy over zero positions. The reframing to at most target zeros in a window is the entire problem.
  • Decrementing the zero count on every left-edge move instead of only when leaving a zero. The count then drifts and the window grows without bound.
  • Recomputing the number of zeros inside the window on each step, which quietly turns the solution into O(n²) while still passing small tests.
  • Not checking target = 0, where the problem degenerates to the longest run of ones. The same loop handles it, but it is worth saying so rather than special-casing it.
  • There is an equivalent non-shrinking variant: replace the while with an if and return len(nums) - l. Because the window then never shrinks, its final size is the maximum. Checked against the shown solution on every binary array up to length 10 for every target, the two always agree — but only because the question asks for a maximum. Reuse that trick on a problem that needs the window contents and it breaks.

Full Solution — all languages

class Solution:
    def longestOnes(self, nums, target):
        l = zeros = best = 0
        for r in range(len(nums)):
            if nums[r] == 0:
                zeros += 1
            while zeros > target:
                if nums[l] == 0:
                    zeros -= 1
                l += 1
            best = max(best, r - l + 1)
        return best
SensAI
Beta
Tap the mic to stop voice mode