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>& nums, int k) {
    int ans = 0;

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      if (nums[r] == 0)
        --k;
      while (k < 0)
        if (nums[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
16
class Solution {
  public int longestOnes(int[] nums, int k) {
    int ans = 0;

    for (int l = 0, r = 0; r < nums.length; ++r) {
      if (nums[r] == 0)
        --k;
      while (k < 0)
        if (nums[l++] == 0)
          ++k;
      ans = Math.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, nums: list[int], k: int) -> int:
    ans = 0

    l = 0
    for r, num in enumerate(nums):
      if num == 0:
        k -= 1
      while k < 0:
        if nums[l] == 0:
          k += 1
        l += 1
      ans = max(ans, r - l + 1)

    return ans