# 487     Max Consecutive Ones II

## 487. [Max Consecutive Ones II](https://leetcode.com/problems/max-consecutive-ones-ii/description/)

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

## 2. Implementation

**(1) Two Pointers**

```java
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**

```java
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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://protegejj.gitbook.io/oj-practices/chapter1/two-pointers/487-max-consecutive-ones-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
