# 487. Max Consecutive Ones II

Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.

Example 1:

``````Input: [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
After flipping, the maximum number of consecutive 1s is 4.
``````

Note:

• The input array will only contain `0` and `1`.
• The length of input array is a positive integer and will not exceed 10,000

What if the input numbers come in one by one as an infinite stream? In other words, you can’t store all numbers coming from the stream as it’s too large to hold in memory. Could you solve it efficiently?

``````class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int res = 0, cur = 0, cnt = 0;
for (int num : nums) {
++cnt;
if (num == 0) {
cur = cnt;
cnt = 0;
}
res = max(res, cnt + cur);
}
return res;
}
};
``````

``````class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int res = 0, zero = 0, left = 0, k = 1;
for (int right = 0; right < nums.size(); ++right) {
if (nums[right] == 0) ++zero;
while (zero > k) {
if (nums[left++] == 0) --zero;
}
res = max(res, right - left + 1);
}
return res;
}
};
``````

``````class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int res = 0, left = 0, k = 1;
queue<int> q;
for (int right = 0; right < nums.size(); ++right) {
if (nums[right] == 0) q.push(right);
if (q.size() > k) {
left = q.front() + 1; q.pop();
}
res = max(res, right - left + 1);
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/487

Max Consecutive Ones

Max Consecutive Ones III

https://leetcode.com/problems/max-consecutive-ones-ii/

https://discuss.leetcode.com/topic/75439/java-concise-o-n-time-o-1-space

https://discuss.leetcode.com/topic/75445/java-clean-solution-easily-extensible-to-flipping-k-zero-and-follow-up-handled

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation