487. Max Consecutive Ones II
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.// Sliding window
int findMaxConsecutiveOnes(vector<int>& nums) { // time: O(n); space: O(1)
int res = 0, zero_cnt = 0, begin = 0, end = 0;
while (end < nums.size()) {
if (nums[end++] == 0) ++zero_cnt;
while (zero_cnt > 1) {
if (nums[begin++] == 0) --zero_cnt;
}
res = max(res, end - begin);
}
return res;
}Last updated