Max Consecutive Ones III

Problem Id: 1004 Difficulty: Medium Tag: Two Pointers Tag: Sliding Window


Intuition

Use 2 index, keep the count of '0' less or equal to K.

Solution


class Solution:
    def longestOnes(self, A: List[int], K: int) -> int:
        count = 0
        lo = 0
        hi = 0
        max_length = 0

        while hi < len(A):
            if A[hi] == 0:
                count += 1
            hi += 1

            while count > K:
                if A[lo] == 0:
                    count -= 1
                lo += 1

            max_length = max(hi - lo + 1, max_length)
        return max_length