Max Consecutive Ones II

Find the longest run of 1s in an array of 0s and 1s when you may turn one 0 into a 1.

You are given an array nums that holds only 0s and 1s. You may change at most one 0 into a 1. Return the length of the longest run of 1s in a row that the array can have after that change.

Example 1
Input: nums = [1, 0, 1, 1, 0]
Output: 4
Explanation: change the first 0 to get [1, 1, 1, 1, 0].
Example 2
Input: nums = [1, 0, 1, 1, 0, 1]
Output: 4
Explanation: changing either 0 gives a run of four 1s.
Solution

The Idea

Picture a row of six lamps, where 1 means on and 0 means off: on, off, on, on, off, on. You may switch on one lamp that is off, and you want the longest row of lit lamps side by side.

That is Example 2, [1, 0, 1, 1, 0, 1]. Switch on the 0 at index 1 and the array becomes [1, 1, 1, 1, 0, 1], with four 1s from index 0 to 3. Switch on the 0 at index 4 instead and it becomes [1, 0, 1, 1, 1, 1], with four 1s from index 2 to 5. Either way the answer is 4.

Trying each 0 in turn works, but it means counting the whole array again for every 0. Is there a way to see the answer without choosing the 0 first?

Look at what a good run is made of. The run from index 0 to 3 was 1, 0, 1, 1 before the change: a stretch of the array with exactly one 0 in it. The run from index 2 to 5 was 1, 1, 0, 1, again one 0. Changing that 0 turns the whole stretch into 1s. A stretch with no 0 at all is already a run of 1s. So the question becomes: what is the longest stretch of the array that holds at most one 0?

A stretch can be marked by two positions, left where it starts and right where it ends. A stretch marked this way is called a window, because we look at the array through it. Look at the picture below, which moves a window along Example 2.

The array 1, 0, 1, 1, 0, 1 with a window. From left 0 to right 3 the window holds one 0, length 4. At right 4 it holds two 0s, which is not allowed. Left moves to 2, so one 0 is left, length 3. At right 5 the window from 2 to 5 has length 4.

In the first row, the window runs from left = 0 to right = 3. It holds one 0, so it is allowed, and its length is 4. In the second row, right moves on to index 4, another 0. Now the window holds two 0s, shown in orange, and only one may be changed.

In the third row, left moves right until the first 0 is out, which puts it at index 2. The 1s at index 2 and 3 stay inside, and the window is allowed again, with length 3. In the last row, right reaches index 5 and the length is 4 again.

So right only moves forward, and left only moves forward when the window holds too many 0s. Neither one ever moves back, so each element enters the window once and leaves it at most once. Two markers that move through the array like this are called two pointers, and a window kept between them is often called a sliding window.

Solution Approach

Turning that idea into code means settling three things: how the window grows, how it shrinks when it holds two 0s, and when to measure it.

Why not try every 0

What would the simple way cost? For each 0, pretend it is a 1 and scan the array for the longest run. An array of n elements can hold up to n zeros, and each scan takes n steps, so this takes about n² steps. For 100,000 elements that is ten billion steps, while the window needs only about 200,000.

Growing the window

How does the window know how many 0s it holds? A counter, zeros, keeps track. Each time right moves on to a new element, that element joins the window, and if it is a 0, zeros goes up by one.

Shrinking the window

What happens when zeros reaches 2? The window must drop elements from its left end until one 0 has gone. Each time left moves past an element, that element leaves the window, and if it was a 0, zeros goes down by one. The 1s between the two 0s stay in the window, as the third row of the picture shows. They are part of the next good run, with the second 0 changed.

Measuring the window

When is the window measured? After every step of right, once the window is allowed again. Its length is right - left + 1, and the 0 inside it, if there is one, counts toward the length because it would be changed to a 1. The longest length seen so far is the answer.

This finds the best run because, for each right, left stops at the furthest-left position that still leaves at most one 0. So each measured window is the longest allowed one ending at right, and the best run is measured when right reaches its last element.

Jumping left past the earlier 0 in one step

As an optional improvement, the code can remember the index of the last 0 it saw. When a new 0 arrives, left jumps to one past that index in a single step, instead of walking there. The total work stays O(n) either way, so the version below keeps the plain walk, which is easier to change to allow more than one 0.

Java Solution

The method findMaxConsecutiveOnes works in these steps:

  1. First, set up three integers: left, the start of the window, at 0; zeros, the number of 0s inside the window, at 0; and best, the longest window so far, at 0.
  2. Move right along the array with a for loop. Each step adds nums[right] to the window, and adds one to zeros if it is a 0.
  3. Inside that loop, a while loop runs as long as zeros is more than 1. It takes nums[left] out of the window, lowers zeros if that element was a 0, and moves left one place right.
  4. With at most one 0 inside, compare the window length right - left + 1 with best and keep the larger.
  5. When right has passed the last element, return best.

The main method runs both examples, an array where the 1s between two 0s matter, an array of only 1s, an array of only 0s, and an empty array.

Java
public class MaxConsecutiveOnesII {

    public static int findMaxConsecutiveOnes(int[] nums) {
        int left = 0;
        int zeros = 0;                        // zeros inside the window nums[left..right]
        int best = 0;
        for (int right = 0; right < nums.length; right++) {
            if (nums[right] == 0) {
                zeros++;
            }
            while (zeros > 1) {               // two zeros: shrink from the left
                if (nums[left] == 0) {
                    zeros--;
                }
                left++;
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(findMaxConsecutiveOnes(new int[] {1, 0, 1, 1, 0}));
        System.out.println(findMaxConsecutiveOnes(new int[] {1, 0, 1, 1, 0, 1}));
        System.out.println(findMaxConsecutiveOnes(new int[] {1, 0, 1, 1, 0, 1, 1}));
        System.out.println(findMaxConsecutiveOnes(new int[] {1, 1, 1}));
        System.out.println(findMaxConsecutiveOnes(new int[] {0, 0, 0}));
        System.out.println(findMaxConsecutiveOnes(new int[] {}));
    }
}

Running it prints:

Output
4
4
5
3
1
0

Look at the first two lines: 4 for [1, 0, 1, 1, 0] and 4 for [1, 0, 1, 1, 0, 1], the answers from the examples.

The third line, 5, comes from [1, 0, 1, 1, 0, 1, 1]. The best run is index 2 to 6, the 1s between the two 0s plus the second 0 and the two 1s after it. To keep that run, left walks just past the first 0 and no further. If the window instead restarted at the second 0, setting left = right, it would lose index 2 and 3 and return 4 for this array.

The fourth line is 3: with no 0 to change, the whole array [1, 1, 1] is already the run. The fifth line is 1, because in [0, 0, 0] only one 0 can become a 1. The last line is 0 for the empty array, since the for loop never runs and best keeps its starting value.

Complexity

The work is one pass of right over the array, plus the steps of left, which never moves back.

  • Time: O(n), for an array of n numbers, because right takes n steps, and across the whole run the while loop moves left at most n steps in total, because left only moves forward and never goes past right.
  • Space: O(1). The method keeps only left, right, zeros and best, however long the array is.

When up to k zeros may be changed instead of one, only the limit in the while check changes: see Max Consecutive Ones III.