# 1004. Max Consecutive Ones III 最大连续1的个数 III

@TOC

## # 题目描述

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

## # 解题方法

### # 虫取法/双指针

[left, right]双闭区间表示一个经过一定次数的翻转后已经全部是1的区间。我们要求的长度就是这个区间的最大长度。我们需要把这个区间内的所有0都翻转成1，使用变量zero统计该区间内的被翻转的0的个数。易知，zero <= K.

C++代码如下：

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

## # 日期

2019 年 3 月 3 日 —— 3月开始，春天到了