Link: 1004. Max Consecutive Ones III

Question

Restate the problem

  • Given an array,
  • Contains binary numbers and an integer k, can flip at most k times zeros to ones.
  • Return the max length of a subarray containing consecutive 1 after at most k flips.

Method

Key idea: Sliding window

Invariant: right - left + 1 count_1 + k

  • Expand the window
    • Move right, include nums[right]
  • Shrink If invalid
    • While window invalid, move left forward until valid again
  • Update result
  • Move right

Complexity

  • Time complexity: O(n)
  • Space complexity: O(1)

Edge case:

  • empty list
class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        res = 0
        zeros = 0
        left = right = 0
        while right < len(nums):
            if nums[right] == 0:
                zeros += 1
            
            while zeros > k:
                if nums[left] == 0:
                    zeros -= 1
                left += 1
            
            res = max(res, right - left + 1)
            right += 1
        
        return res

History

Jan-23-2026 Solved

  • Inclusive window: length = right_idx − left_idx + 1