Link: 1004. Max Consecutive Ones III
Question
Restate the problem
- Given an array,
- Contains binary numbers and an integer
k, can flip at mostktimes zeros to ones. - Return the max length of a subarray containing consecutive
1after at mostkflips.
Method
Key idea: Sliding window
Invariant: right - left + 1 ⇐ count_1 + k
- Expand the window
- Move right, include
nums[right]
- Move right, include
- Shrink If invalid
- While window invalid, move
leftforward until valid again
- While window invalid, move
- 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 resHistory
Jan-23-2026 Solved
- Inclusive window: length = right_idx − left_idx + 1