1004. Max Consecutive Ones III

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.

分析:
用两个指针: start, end. 不断往前移动end,当arr[end]是0的话,count--。如果count < 0,那么就往前移动start, 然后不断比较global_max和 end - start + 1. 
 1 class Solution {
 2     public int longestOnes(int[] nums, int k) {
 3         int max = 0, start = 0;
 4         for (int end = 0; end < nums.length; end++) {
 5             if (nums[end] == 0) {
 6                 k--;
 7             }
 8             while (k < 0) {
 9                 if (nums[start] == 0) {
10                     k++;
11                 }
12                 start++;
13             }
14             max = Integer.max(max, end - start + 1);
15         }
16         return max;
17     }
18 }

 

posted @ 2020-01-31 00:05  北叶青藤  阅读(155)  评论(0)    收藏  举报