Max consecutive ones III

October 28, 2022

sliding-window

Problem URL: Max consecutive ones III

We basically need to find the longest subarray with at most k zeros. We can use the sliding window technique to get that.

class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        i = 0
        for j in range(len(nums)):
            k -= 1-nums[j]
            if k < 0:
                k += 1-nums[i]
                i += 1
        return j-i+1

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