Leetcode 1046 Solution

This article provides solution to leetcode question 1046 (max-consecutive-ones-iii)

https://leetcode.com/problems/max-consecutive-ones-iii

Solution

class Solution:
    def longestOnes(self, A: List[int], K: int) -> int:
        l = 0
        r = 0
        zero_no = 0
        ans = 0

        while r < len(A):
            if A[r] == 1:
                r += 1
            else:
                if zero_no < K:
                    r += 1
                    zero_no += 1
                else:
                    while A[l] == 1:
                        l += 1
                    l += 1
                    zero_no -= 1

            ans = max(r - l, ans)

        return ans