Max Consecutive Ones III

MediumSliding Window · At Most K Bad🧩 Sliding WindowLeetCode #1004 ↗Updated

Problem

Given a binary array nums and an integer k, you may turn at most k zeros into ones. Return the length of the longest run of consecutive ones you can achieve.
Inputnums = [1,1,1,0,0,0,1,1,1,1,0], k = 2Output6
Inputnums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3Output10
Inputnums = [0,0,0], k = 0Output0

1 ≤ n ≤ 105  ·  nums[i] is 0 or 1  ·  0 ≤ k ≤ n

Try it yourself

Java
class Solution {
    public int longestOnes(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Rephrase it: find the longest subarray containing at most k zeros. That constraint only gets worse as a window grows, so a two-pointer window that shrinks from the left whenever it holds too many zeros visits each index twice at most.
PatternSliding Window

Instinct Longest, shortest or count of contiguous subarrays/substrings meeting a rule? Grow a window on the right, shrink it on the left, never step back.

Memory hack Move like a caterpillar - the head stretches forward to grab, the tail pulls up only when the body breaks the rule.

Open the Sliding Window guide →

Approaches

Brute ForceExtend from Every Start

Time O(n2)Space O(1)

For each start i, walk j rightwards counting zeros and stop as soon as the count exceeds k. The last valid j gives the longest flip-able run starting at i.

Java
public int longestOnes(int[] nums, int k) {
    int n = nums.length, best = 0;
    for (int i = 0; i < n; i++) {
        int zeros = 0;
        for (int j = i; j < n; j++) {
            if (nums[j] == 0) zeros++;
            if (zeros > k) break; // budget exceeded
            best = Math.max(best, j - i + 1);
        }
    }
    return best;
}

Correct and tiny, but an all-ones array costs n2/2 steps.

At a glance

LevelApproachTimeSpace
Brute ForceExtend from Every StartO(n2)O(1)
BetterPrefix Zero Counts + Binary SearchO(n log n)O(n)
OptimalSliding Window with Zero BudgetO(n)O(1)
Common pitfalls
  • Trying to choose which zeros to flip — the window decides that implicitly.
  • Decrementing zeros when a 1 leaves the window.
  • Forgetting k = 0: the answer is then the longest existing run of ones.
Interview tips
  • Restate the problem as “longest subarray with at most k zeros” out loud.
  • Argue O(n): left and right each move at most n times.
  • Link it to LC 424 — same window, different notion of “bad” element.
Pattern
Variable sliding window with a counter → longest range where some count stays ≤ k.
My notes saved in this browser