1004. Max Consecutive Ones III - cocoder39/coco39_LC GitHub Wiki

1004. Max Consecutive Ones III

key point is to convert the problem to the typical sliding window problem

class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        left = 0
        res = 0
        for right in range(len(nums)):
            if nums[right] == 0:
                k -= 1
            if k < 0:
                while left < right and nums[left] == 1:
                    left += 1
                left += 1
                k += 1
            
            #print(left, right)
            res = max(res, right-left+1)
        return res