给定一个二进制数组 nums
和一个整数 k
,如果可以翻转最多 k
个 0
,则返回 数组中连续 1
的最大个数 。
示例 1:
输入:nums = [1,1,1,0,0,0,1,1,1,1,0], K = 2 输出:6 解释:[1,1,1,0,0,1,1,1,1,1,1] 粗体数字从 0 翻转到 1,最长的子数组长度为 6。
示例 2:
输入:nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3 输出:10 解释:[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] 粗体数字从 0 翻转到 1,最长的子数组长度为 10。
提示:
1 <= nums.length <= 10^5
nums[i]
不是0
就是1
0 <= k <= nums.length
提示 1
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window!
提示 2
Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right?
提示 3
We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!).
提示 4
The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
解法:滑动窗口
class Solution {
public int longestOnes(int[] nums, int k) {
int ans = 0;
// valid 存储窗口内的0的数量
int valid = 0;
int left = 0;
int right = 0;
while (right < nums.length) {
if (nums[right] == 0) {
valid++;
}
while (valid > k) {
if (nums[left] == 0) {
valid--;
}
left++;
}
ans = Math.max(ans, right - left + 1);
right++;
}
return ans;
}
}
复杂度分析
- 时间复杂度:O(N),N是数组的长度。
- 空间复杂度:O(1)。