Given a binary array nums
, return the maximum number of consecutive 1
's in the array if you can flip at most one 0
.
Example 1:
Input: nums = [1,0,1,1,0] Output: 4 Explanation: Flip the first zero will get the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4.
Example 2:
Input: nums = [1,0,1,1,0,1] Output: 4
Constraints:
1 <= nums.length <= 105
nums[i]
is either0
or1
.
思路:滑动窗口,就是at most 1的马甲;模板走起。
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int maxlen = 0;
int j = 0;
int count = 0;
for(int i = 0; i < nums.length; i++) {
// move j;
while(j < nums.length && count <= 1) {
if(nums[j] == 0) {
if(count == 1) {
break;
}
count++;
}
j++;
}
// update res;
maxlen = Math.max(maxlen, j - i);
//move i;
if(nums[i] == 0) {
count--;
}
}
return maxlen;
}
}