[LeetCode] Max Consecutive Ones II

487. Max Consecutive Ones II

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& A) {
int start = 0, res = 0, n = A.size(), cur = 0, prv = 0;
for(int i = 0; i < n; i++) {
if(A[i]) {
if(!cur) start = i;
res = max(res, ++cur + (start > 0) + prv);
} else {
res = max(res, cur + 1);
prv = cur;
cur = 0;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/18/PS/LeetCode/max-consecutive-ones-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.