487 Max Consecutive Ones II

1. Question

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 contain0and1.

  • 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?

2. Implementation

(1) Two Pointers

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

        int k = 1;
        int zeroes = 0;
        int maxLen = 0, start = 0, end = 0;

        while (end < nums.length) {
            if (nums[end] == 0) {
                ++zeroes;
            }
            ++end;

            while (zeroes > k) {
                if (nums[start] == 0) {
                    --zeroes;
                }
                ++start;
            }
            maxLen = Math.max(maxLen, end - start);
        }
        return maxLen;
    }
}

Follow Up

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

        int k = 1;
        int maxLen = 0;
        Queue<Integer> zeroIndex = new LinkedList<>();

        for (int start = 0, end = 0; end < nums.length; end++) {
            if (nums[end] == 0) {
                zeroIndex.add(end);
            }

            if (zeroIndex.size() > k) {
                start = zeroIndex.remove() + 1;
            }
            maxLen = Math.max(maxLen, end - start + 1);
        }
        return maxLen;
    }
}

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n), 空间复杂度O(1)

Follow up: 时间复杂度O(n), 空间复杂度O(k)

Last updated