给定一个由若干 0
和 1
组成的数组 A
,我们最多可以将 K
个值从 0 变成 1 。
返回仅包含 1 的最长(连续)子数组的长度。
题解:依次把遇到的变为1,如果变的次数超过了K,就把左边第一个变过的取消掉。
class Solution {
public int longestOnes(int[] A, int K) {
int res = 0;
int left = 0;
int zero = 0;
int N = A.length;
for (int right = 0; right < N; ++right) {
if (A[right] == 0)
++zero;
while (zero > K) {
if (A[left++] == 0)
--zero;
}
res = Math.max(res, right - left + 1);
}
return res;
}
}