【题目描述】
给定一个二进制数组 nums
k
,如果可以翻转最多 k
个 0
,则返回 数组中连续 1
的最大个数 。
https://leetcode.cn/problems/max-consecutive-ones-iii/
【示例】
【代码】负雪明烛
思路: 滑动窗口
package com.company;
import java.util.Arrays;
import java.util.Stack;
// 2022-02-16
class Solution {
public int longestOnes(int[] nums, int k) {
int len = nums.length;
int res = 0;
int left = 0;
int right = 0;
int zero = 0;
while (right < len){
if (nums[right] == 0) zero++;
while (zero > k) {
if (nums[left++] == 0)
zero--;
}
res = Math.max(res, right - left + 1);
right++;
}
System.out.println(res);
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().longestOnes(new int[] {1,1,1,0,0,0,1,1,1,1,0}, 2); // 输出: 6
new Solution().longestOnes(new int[] {0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1}, 3); // 输出: 10
}
}