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 <= A.length <= 20000
0 <= K <= A.length
A[i]
is0
or1
最大连续1的个数 III。
给定一个由若干 0
和 1
组成的数组 A
,我们最多可以将 K
个值从 0 变成 1 。返回仅包含 1 的最长(连续)子数组的长度。
这是一道比较典型的滑动窗口类型的题目,我们可以直接套用76题的模板。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int longestOnes(int[] A, int K) { 3 int start = 0; 4 int end = 0; 5 int count = 0; 6 int res = 0; 7 while (end < A.length) { 8 if (A[end] == 0) { 9 count++; 10 } 11 // K用完了的时候就要开始缩减窗口范围 12 while (count > K) { 13 if (A[start] == 0) { 14 count--; 15 } 16 start++; 17 } 18 // 计算窗口大小 19 res = Math.max(res, end - start + 1); 20 end++; 21 } 22 return res; 23 } 24 }
LeetCode中有如下一些题目,求的是连续出现的数字或者字母最长可以组成的子串长度,本质上还是滑动窗口类型的题目。
1004. Max Consecutive Ones III