# 1004. Max Consecutive Ones III

Given an array `A` of 0s and 1s, we may change up to `K` values from 0 to 1.

Return the length of the longest (contiguous) subarray that contains only 1s.

Example 1:

``````Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.
``````

Example 2:

``````Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.
``````

Note:

1. `1 <= A.length <= 20000`
2. `0 <= K <= A.length`
3. `A[i]` is `0` or `1`

``````class Solution {
public:
int longestOnes(vector<int>& A, int K) {
int n = A.size(), left = 0, cnt = 0, res = 0;
for (int i = 0; i < n; ++i) {
if (A[i] == 0) ++cnt;
while (cnt > K) {
if (A[left] == 0) --cnt;
++left;
}
res = max(res, i - left + 1);
}
return res;
}
};
``````

``````class Solution {
public:
int longestOnes(vector<int>& A, int K) {
int n = A.size(), i = 0, j = 0;
for (; j < n; ++j) {
if (A[j] == 0) --K;
if (K < 0 && A[i++] == 0) ++K;
}
return j - i;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1004

Number of Substrings Containing All Three Characters

Count Number of Nice Subarrays

Replace the Substring for Balanced String

Binary Subarrays With Sum

Shortest Subarray with Sum at Least K

Minimum Size Subarray Sum

Longest Substring with At Most Two Distinct Characters

Longest Substring with At Least K Repeating Characters

Longest Substring with At Most K Distinct Characters

Max Consecutive Ones II

Max Consecutive Ones

https://leetcode.com/problems/max-consecutive-ones-iii/

https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247564/JavaC%2B%2BPython-Sliding-Window

https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247543/O(n)-Java-Solution-using-sliding-window

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation