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
class Solution { public int longestOnes(int[] arr, int k) { int res = 0, start = 0; int ocount = 0; for(int end = 0; end < arr.length; end++) { if(arr[end] == 1) ocount++; while(end - start + 1 - ocount > k) { if(arr[start] == 1) ocount--; start++; } res = Math.max(res, end - start + 1); } return res; } }
这题也是sliding window,是上面那道题的简化版,window维护啥呢?维护在k次改变下能生成的最长1子串。上个题有26个字母,这个只有0和1,而且要求要是1子串
开始,如果当前数字==1,onecount++,如果当前window包不住了,就要start++,注意啊如果arr【start】==1了菜肴onecount--。