---
# System prepended metadata

title: 1004. Max Consecutive Ones III
tags: [Leetcode, Sliding Window, Medium]

---

# 1004. Max Consecutive Ones III
###### tags: `Leetcode` `Medium` `Sliding Window`
Link: https://leetcode.com/problems/max-consecutive-ones-iii/

## 思路
Sliding window感觉上就是一直用l和r把符合条件的答案包起来，然后在遍历过程中算最小或最大值

**Sliding Window 模板**
[Sliding Window模板](https://leetcode-cn.com/problems/max-consecutive-ones-iii/solution/fen-xiang-hua-dong-chuang-kou-mo-ban-mia-f76z/)
```java=
int N = nums.length();
int l,r,res,sum = 0;
while(r<N){
    sum+=nums[r];//增加当前右边指针的数字/字符的求和/计数
    while 区间[l,r]不符合题意{
        sum-=nums[l++];
    }
    res = Math.max(res,r-l+1)；
}
return res;
```
## Code
```java=
class Solution {
    public int longestOnes(int[] nums, int k) {
        int l = 0;
        int r = 0;
        int cntZero = 0;
        int maxWindow = 0;
        while(r<nums.length){
            if(nums[r]==0){
                cntZero++;
            }
            while(cntZero>k){
                if(nums[l++]==0){
                    cntZero--;
                }
            }
            maxWindow = Math.max(maxWindow, r-l+1);
            r++;
        }
        return maxWindow;
    }
}
```