LeetCode 487. Max Consecutive Ones II

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int cur = 0, cnt = 0, ans = 0;
for (int num : nums) {
++cnt;
if (num == 0) {
cur = cnt;
cnt = 0;
}
ans = max(ans, cur + cnt);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int n = nums.size(), left = 0, right = 0, cnt = 0, ans = 0;
while (right < n) {
if (nums[right++] == 0)
++cnt;
while (cnt > 1)
if (nums[left++] == 0)
--cnt;
ans = max(ans, right - left);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// solution for follow up (nums as streaming data).
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int n = nums.size(), left = 0, right = 0, ans = 0;
queue<int> q;
while (right < n) {
if (nums[right++] == 0)
q.push(right);
if (q.size() > 1) {
left = q.front(); q.pop();
}
ans = max(ans, right - left);
}
return ans;
}
};