LeetCode Solutions

487. Max Consecutive Ones II

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int findMaxConsecutiveOnes(vector<int>& nums) {
    int ans = 0;
    int zeros = 0;

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

    return ans;
  }
};
			

class Solution {
  public int findMaxConsecutiveOnes(int[] nums) {
    int ans = 0;
    int zeros = 0;

    for (int l = 0, r = 0; r < nums.length; ++r) {
      if (nums[r] == 0)
        ++zeros;
      while (zeros == 2)
        if (nums[l++] == 0)
          --zeros;
      ans = Math.max(ans, r - l + 1);
    }

    return ans;
  }
}
			

class Solution:
  def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
    ans = 0
    zeros = 0

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

    return ans