• Time:O(n)
• Space:O(1)

## C++

``````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;
}
};
``````

## JAVA

``````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;
}
}
``````

## Python

``````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
``````

• Time:O(n)
• Space:O(1)

## C++

``````class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
constexpr int maxZeros = 1;
int ans = 0;
queue<int> q;  // store indices of zero

for (int l = 0, r = 0; r < nums.size(); ++r) {
if (nums[r] == 0)
q.push(r);
if (q.size() > maxZeros)
l = q.front() + 1, q.pop();
ans = max(ans, r - l + 1);
}

return ans;
}
};
``````

## JAVA

``````class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
final int maxZeros = 1;
int ans = 0;
// store indices of zero
Queue<Integer> q = new ArrayDeque<>();

for (int l = 0, r = 0; r < nums.length; ++r) {
if (nums[r] == 0)
q.offer(r);
if (q.size() > maxZeros)
l = q.poll() + 1;
ans = Math.max(ans, r - l + 1);
}

return ans;
}
}
``````

## Python

``````class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
maxZeros = 1
ans = 0
q = deque()  # store indices of zero

l = 0
for r, num in enumerate(nums):
if num == 0:
q.append(r)
if len(q) > maxZeros:
l = q.popleft() + 1
ans = max(ans, r - l + 1)

return ans
``````

• Time:O(n)
• Space:O(1)

## C++

``````class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int ans = 0;
int lastZeroIndex = -1;

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

return ans;
}
};
``````

## JAVA

``````class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int ans = 0;
int lastZeroIndex = -1;

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

return ans;
}
}
``````

## Python

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

l = 0
for r, num in enumerate(nums):
if num == 0:
l = lastZeroIndex + 1
lastZeroIndex = r
ans = max(ans, r - l + 1)

return ans
``````