首页 > 代码库 > 487. Max Consecutive Ones II

487. Max Consecutive Ones II

Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.

Example 1:

Input: [1,0,1,1,0]
Output: 4
Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
    After flipping, the maximum number of consecutive 1s is 4.

 

Note:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

 

Follow up:
What if the input numbers come in one by one as an infinite stream? In other words, you can‘t store all numbers coming from the stream as it‘s too large to hold in memory. Could you solve it efficiently?

 

本题我开始用了一个方法跑了出来,但是对于one变成了多个的话就解决不了了,后来看了答案,发现可以用zero来表示出现zero的个数,然后while zero出现的次数大于k的时候把后面的指针往前移。代码如下:

 1 public class Solution {
 2     public int findMaxConsecutiveOnes(int[] nums) {
 3         int hi = 0;
 4         int lo = 0;
 5         int zero = 0;
 6         int len = 0;
 7         while(hi<nums.length){
 8             if(nums[hi]==0){
 9                 zero++;
10             }
11             while(zero>1){
12                 if(nums[lo++]==0) zero--;
13             }
14             len = Math.max(len,hi-lo+1);
15             hi++;
16         }
17         return len;
18     }
19 }

对于出现的follow up,可以使用一个queue来做,其他的方法还是上面的方法,代码如下:

 1 public class Solution {
 2     public int findMaxConsecutiveOnes(int[] nums) {
 3         Queue<Integer> q = new LinkedList<Integer>();
 4         int hi = 0;
 5         int lo = 0;
 6         int len = 0;
 7         for(;hi<nums.length;hi++){
 8             if(nums[hi]==0){
 9                 q.offer(hi);
10             }
11             while(q.size()>1){
12                 lo = q.poll()+1;
13             }
14             len = Math.max(len,hi-lo+1);
15         }
16         return len;
17     }
18 }

 

487. Max Consecutive Ones II