DSA and coding Level 2 This level · 21 of 30
Medium dsa sliding-window

Max Consecutive Ones III

The 30 second answer

I may flip at most k zeros to ones, and I want the longest run of ones I can make. That is a variable window that may contain at most k zeros. I grow the window, count zeros, shrink from the left when the count exceeds k, and keep the longest valid length.

Could you say this in an interview?

Problem Given a binary array and an integer k, you may flip at most k zeros to ones. Return the length of the longest contiguous subarray of ones you can achieve. Original: LeetCode 1004: Max Consecutive Ones III.

Understanding the prompt Flips only help inside the chosen window. k = 0 means you must use an existing run of ones. If k is at least the number of zeros, the answer is the whole array.

Pattern recognition Variable-size window, constraint 'at most k zeros'. It is the binary special case of Longest Repeating Character Replacement.

Brute force For every start, extend right and count zeros until you exceed k: O(n²).

Optimal A left edge and a zero counter. Add nums[hi], and while zeros > k, if nums[lo] is zero decrement the counter, then advance lo. The length hi − lo + 1 is a candidate after each step.

Alternatives Treat zeros as the letter you are willing to replace, and reuse the character-replacement window with a two-letter alphabet.

Java solution

public class MaxConsecutiveOnesIII {
    static int longestOnes(int[] nums, int k) {
        int lo = 0, zeros = 0, best = 0;
        for (int hi = 0; hi < nums.length; hi++) {
            if (nums[hi] == 0) zeros++;
            while (zeros > k) {
                if (nums[lo++] == 0) zeros--;
            }
            best = Math.max(best, hi - lo + 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)); // 6
        System.out.println(longestOnes(new int[] {0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1}, 3)); // 10
    }
}

Complexity O(n) time, O(1) extra space.

Edge cases

  • k = 0, which reduces to the longest existing run of ones.
  • Official samples: [1,1,1,0,0,0,1,1,1,1,0] with k = 2 returns 6; the longer official sample with k = 3 returns 10.

Follow-ups

  • Longest Repeating Character Replacement is the same pattern on letters.
  • You must flip exactly k zeros: shrink until the window contains exactly k zeros, not at most k.

Tests [1,1,1,0,0,0,1,1,1,1,0] with k=2 returns 6. [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1] with k=3 returns 10.

How to say it in the interview "I want the longest window that contains at most k zeros, because those are the flips I can afford. I grow the window, shrink from the left when I have too many zeros, and keep the longest valid length. Linear time, constant space."

Sources (1)
  1. LeetCode 1004: Max Consecutive Ones IIIleetcode.com
Previous
Next