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?

Rust Solution

struct Solution;
use std::collections::VecDeque;

impl Solution {
    fn find_max_consecutive_ones(nums: Vec<i32>) -> i32 {
        let n = nums.len();
        let mut res = 0;
        let mut queue: VecDeque<usize> = VecDeque::from(vec![0, 0]);
        for i in 0..n {
            *queue.back_mut().unwrap() += 1;
            if nums[i] == 0 {
                queue.pop_front();
                queue.push_back(0);
            }
            res = res.max(queue.iter().sum());
        }
        res as i32
    }
}

#[test]
fn test() {
    let nums = vec![1, 0, 1, 1, 0];
    let res = 4;
    assert_eq!(Solution::find_max_consecutive_ones(nums), res);
    let nums = vec![1, 1, 0, 1];
    let res = 4;
    assert_eq!(Solution::find_max_consecutive_ones(nums), res);
}

Having problems with this solution? Click here to submit an issue on github.