Skip to content

1004. Max Consecutive Ones III 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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
Back to top