LeetCode Solutions

1004. Max Consecutive Ones III

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int longestOnes(vector<int>& A, int K) {
    int ans = 0;

    for (int l = 0, r = 0; r < A.size(); ++r) {
      if (A[r] == 0)
        --K;
      while (K < 0)
        if (A[l++] == 0)
          ++K;
      ans = max(ans, r - l + 1);
    }

    return ans;
  }
};
			

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

    l = 0
    for r, a in enumerate(A):
      if a == 0:
        K -= 1
      while K < 0:
        if A[l] == 0:
          K += 1
        l += 1
      ans = max(ans, r - l + 1)

    return ans