@yuxiangmusic

In fact, there is a much easier solution which only needs scan the array from head to tail once. Same for the follow-up situations.

Here is the link. There are detailed explanations.

int findMaxConsecutiveOnes(vector<int>& nums) {
int k = 1; // flip at most k zeros
vector<int> cnt(k + 1, 0);
int res = 0;
for (int i: nums) {
if (i == 1) {
for (int &c: cnt) {
++c;
}
} else {
res = max(res, cnt[k]);
for (int j = k; j > 0; --j) {
cnt[j] = 1 + cnt[j - 1];
}
cnt[0] = 0;
}
}
for (int i: cnt) {
res = max(res, i);
}
return res;
}