Tensorum
LeetCode 1004 · Variable Window – Longest

Max Consecutive Ones III

LeetCode 1004 · Medium · solution, intuition & step-by-step walkthrough

Longest window with ≤ k zeros.

MediumArrayBinary SearchSliding WindowPrefix Sum
97 msruntime · beats 10%
20.4 MBmemory · beats 100%
1approach
8accepted runs · last 17 Aug 2025

This is how I solved Max Consecutive Ones III (LeetCode 1004), a medium problem from the Variable Window – Longest pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Flipping at most k zeros means: find the longest window containing at most k zeros. Grow the window to the right; when it holds too many zeros, slide the left edge.

Approach

  1. 1

    Count zeros in the window.

  2. 2

    If zeros > k, move l right (decrement if a zero leaves).

  3. 3

    Track the window length.

How I solved it

Sliding windowPythonO(n) time · O(1) space
class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        #sliding window and two pointer
        #count the number of zeroes in the current window
        #if it exceeds, shrink from left, take care of count of 0 - left most position
        l=0
        r=0
        cnt_zeros = 0
        max_length = float("-inf")
        while r<len(nums):
            cur = nums[r]
            if cur==0:
               cnt_zeros+=1
            if cnt_zeros>k:
                if nums[l]==0:
                    cnt_zeros-=1
                l+=1
            max_length=max(max_length,r-l+1)
            r+=1
        return max_length
Loading the step-through…

Max Consecutive Ones III — FAQ

What is the intuition behind Max Consecutive Ones III?

Flipping at most k zeros means: find the longest window containing at most k zeros. Grow the window to the right; when it holds too many zeros, slide the left edge.

How do you solve Max Consecutive Ones III (LeetCode 1004)?

1. Count zeros in the window. 2. If zeros > k, move l right (decrement if a zero leaves). 3. Track the window length.

What is the time and space complexity of Max Consecutive Ones III?

Time: O(n). Space: O(1). (Accepted approach: Sliding window.)

What are common mistakes in Max Consecutive Ones III?

The window never shrinks, only slides — that's fine because we only need the max length.