0487. Max Consecutive Ones II

https://leetcode.com/problems/max-consecutive-ones-ii

Description

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

Example 1:

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

Example 2:

**Input:** nums = [1,0,1,1,0,1]
**Output:** 4

Constraints:

  • 1 <= nums.length <= 105

  • nums[i] is either 0 or 1.

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?

ac1: 2 pointers

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        // edge cases
        if (nums == null || nums.length == 0) return 0;

        int f = 0, s = 0, len = 0, zero = -1;
        for (; f < nums.length; f++) {
            if (nums[f] == 1) continue;
            if (nums[f] == 0) {
                if (zero == -1) {  // first 0, flip
                    zero = f;
                    continue;
                } else {  // not 1st zero
                    len = Math.max(len, f - s);
                    s = zero + 1;
                    zero = f;
                }
            }
        }
        len = Math.max(len, f - s);

        return len;
    }
}

ac2: sliding window

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        // edge cases
        if (nums == null || nums.length == 0) return 0;

        int len = 0, k = 1;
        Queue<Integer> q = new LinkedList<>();

        for (int f = 0, s = 0; f < nums.length; f++) {
            if (nums[f] == 0) q.offer(f);

            while (q.size() > k) {
                s = q.poll() + 1;
            }

            len = Math.max(len, f - s + 1);
        }

        return len;
    }
}

Last updated