思路
- 滑动窗口法
- condition就是0的个数,来决定是否向左滑,或向右滑
while(l<=r&&r<len){
while(r<len&&condition1){//左边窗口
if(condition2)
处理;
r++;
}
while(l<=r&&condition3){//右边窗口
if(condition4)
处理;
l++;
}
}
代码
#include<stdio.h>
#define Max(a,b) ((a)>(b)?a:b)
int findMaxConsecutiveOnes(int* nums, int numsSize){
int l = 0,r=0;
int count0=0;
int res = 0;
while (r<numsSize&&l<=r)
{
while (r<numsSize&&count0<=1)
{
if(nums[r]==0){
count0++;
}
if(count0<2)
res = Max(res,r-l+1);
r++;
}
while (l<=r&&count0>1)
{
if(nums[l]==0){
count0 --;
}
l++;
}
}
return res;
}
int main(){
int nums[] = {1,0,1,1,0};
int res = findMaxConsecutiveOnes(nums,5);
printf("re = %d\n",res);
}