Max Consecutive Ones III

Find the longest run of 1s in an array of 0s and 1s when up to k of the 0s may be changed to 1s.

Given an array nums that holds only 0s and 1s, and a number k, you may change at most k of the 0s into 1s. Return the largest number of consecutive 1s, meaning 1s that sit next to each other with nothing in between, that the array can have after these changes.

Example 1
Input: nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 2
Output: 6
Explanation: change the 0s at index 5 and index 10 into 1s, and index 5 to 10 is a run of six 1s.
Example 2
Input: nums = [0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], k = 3
Output: 10
Explanation: change the 0s at index 4, 5 and 9 into 1s, and index 2 to 11 is a run of ten 1s.
Solution

The Idea

Picture a row of eleven light bulbs: on, on, on, off, off, off, on, on, on, on, off. Write on as 1 and off as 0, and you have Example 1. You may switch on at most two bulbs, because k = 2, and you want the longest row of lit bulbs side by side.

Where should the two switches go? Switching on the bulbs at index 3 and 4 joins them to the three 1s on their left, so index 0 to 4 is a run of five. Switching on index 4 and 5 instead joins them to the four 1s at index 6 to 9, a run of six. Trying every choice of zeros works for eleven bulbs, but the choices multiply fast. Can we find the answer without choosing zeros at all?

Turn the question around and look at stretches instead. A stretch is a run of positions next to each other, such as index 4 to 9. It can become all 1s exactly when it holds at most k zeros, because each zero needs one switch. So the real question is: what is the longest stretch with at most k zeros? The zeros to change are then simply the ones inside it.

To search the stretches, use two markers, left and right, and call every position from left to right the window. right moves one step at a time and takes in a new number. When the window holds too many zeros, left moves forward until it holds few enough again. Look at the picture below. The blue outline is the window, and the orange cells are the zeros inside it, the ones that would be changed.

Three rows of the array 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0 with k = 2. At right = 4 the window is index 0 to 4: 2 zeros, length 5. At right = 5 a third zero comes in, so left moves past index 3 to index 4. At right = 9 the window is index 4 to 9: 2 zeros, length 6.

In the row labelled right = 4, the window covers index 0 to 4. It holds 2 zeros, which is allowed, and its length is 5. In the row labelled right = 5, right has taken in a third zero, one too many. So left moves forward until a zero leaves: past the 1s at index 0 to 2, then past the 0 at index 3, to stop at index 4.

In the row labelled right = 9, right has taken in four more 1s. The window from index 4 to 9 holds 2 zeros and has length 6, the answer. It is a different stretch from the one in Example 1's explanation, index 5 to 10, but just as long.

Moving one marker forward and pulling the other after it is called a sliding window. Both markers only ever move forward, so each position enters the window once and leaves it at most once.

Solution Approach

Turning that idea into code means settling three things: how to know the number of zeros in the window, when to move left, and when to record the answer.

Counting the zeros in the window

How do we know how many zeros the window holds without looking through it every time? Keep a counter, zeros. When right takes in a 0, add one, and when left moves past a 0, take one off.

Without the counter, the simple way is to try every start and every end and count the zeros in each. For an array of n numbers that is about n²/2 stretches, or 50 million for 10,000 numbers. The counter lets a single pass do the same job.

Shrinking the window

When should left move? Only when zeros goes above k. Then left steps forward, and zeros drops by one each time the number it moves past is a 0. right added only one zero, so one zero leaving makes the window allowed again.

Why is it safe never to move left back? A window that starts further left already held too many zeros up to the current right. Moving right on can only add zeros, so that start never becomes allowed again.

Recording the longest window

When is the window worth measuring? After the shrinking, it holds at most k zeros, so all of it can become 1s. Its length is right - left + 1, and a variable best keeps the largest length seen so far.

Java Solution

The method longestOnes works in these steps:

  1. First, set three variables to 0: left, the start of the window; zeros, the number of 0s inside it; and best, the longest window seen so far.
  2. A for loop moves right from the first index to the last. When nums[right] is 0, add one to zeros.
  3. Inside that loop, a while loop runs as long as zeros is greater than k. Each time, if nums[left] is 0, take one off zeros, then move left forward.
  4. The window from left to right now holds at most k zeros. Compare its length, right - left + 1, with best and keep the larger.
  5. After right has reached the last index, return best, the longest stretch that needed at most k changes.

The main method runs both examples, k = 0 on [1, 1, 0, 1, 1, 1], an array of only zeros with k = 0, and a k larger than the number of zeros.

Java
public class MaxConsecutiveOnesIII {

    public static int longestOnes(int[] nums, int k) {
        int left = 0;
        int zeros = 0;                        // zeros in nums[left..right]
        int best = 0;
        for (int right = 0; right < nums.length; right++) {
            if (nums[right] == 0) {
                zeros++;
            }
            while (zeros > k) {               // more zeros than flips: shrink
                if (nums[left] == 0) {
                    zeros--;
                }
                left++;
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(longestOnes(new int[] {1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0}, 2));
        int[] b = {0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1};
        System.out.println(longestOnes(b, 3));
        System.out.println(longestOnes(new int[] {1, 1, 0, 1, 1, 1}, 0));
        System.out.println(longestOnes(new int[] {0, 0, 0}, 0));
        System.out.println(longestOnes(new int[] {0, 1, 0, 1}, 5));
    }
}

Running it prints:

Output
6
10
3
0
4

Example 1 gives 6 and Example 2 gives 10, as expected. In the third line, k = 0 allows no changes, so 3 is simply the longest run of 1s already in [1, 1, 0, 1, 1, 1], at index 3 to 5.

The fourth line is 0. Every 0 in [0, 0, 0] is one zero too many, so left moves past it at once and the window is always empty. In the last line, k = 5 is more than the two zeros in [0, 1, 0, 1], so the whole array counts and the answer is its length, 4.

The while condition has to be zeros > k, not zeros >= k. With >=, the window lets a zero go as soon as it holds k of them, so it never keeps more than k - 1. Run on Example 1, that version returns 5 instead of 6.

Complexity

The work is one pass of right over the array, plus the steps of left that follow it.

  • Time: O(n), because right visits each of the n numbers in nums once. left only moves forward, so the while loop runs at most n times over the whole method, not n times per step of right.
  • Space: O(1). The method keeps only left, right, zeros and best, however long the array is, and reads nums without copying it.

With k = 1, only one 0 may change, and the same window solves Max Consecutive Ones II.

The same window works on letters too. In Longest Repeating Character Replacement, the letters to change are the ones that differ from the most common letter in the window.