Browse curriculum

Max Consecutive Ones III (LeetCode 1004)

Max Consecutive Ones III (LeetCode 1004): find the longest run of 1s after flipping at most k zeros, as the longest sliding window containing at most k zeros.

Problem Understanding

Max Consecutive Ones III: given a binary array and an integer k, return the maximum number of consecutive 1s you can get if you may flip at most k zeros to 1.

Example: nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 2 returns 6: flip the two zeros at indices 4 and 5.

The Intuition: A Window With a Zero Budget

Don't actually flip anything. A run of 1s after flipping is just a window of the original array that holds at most k zeros; those zeros are the ones you would flip. So look for the longest such window with a variable-size sliding window:

  1. Extend right, counting zeros as they enter.
  2. If the count goes above k, move left forward until a zero leaves.
  3. The window is valid again; record right − left + 1 if it is the longest.

Each index enters and leaves at most once, so this is O(n). The same "budget" shape appears in Longest Repeating Character Replacement, where the budget is replacements instead of zeros.

Max Consecutive Ones III Visualization

AT MOST k = 2 ZEROS IN THE WINDOW · DASHED ZEROS ARE FLIPPED

EMPTY WINDOW

1

0

1

1

1

2

0

3

0

4

0

5

1

6

1

7

1

8

1

9

0

10

zeros

0

best

:

Answer

:

 

Find the longest window with at most k = 2 zeros: those zeros are the ones flipped

Next

Add nums[0] = 1

Free preview: the first 9 of 29 steps

nums

k

The window L..R is shaded and the zeros inside it are dashed amber: those are the flips being spent. Watch the window slide forward whenever one zero too many comes in.

Max Consecutive Ones III Dry Run

Input: [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 2

right Window Zeros Length
4 0..4 2 5
5 4..5 after shrinking past index 3 2 2
9 4..9 2 6
10 5..10 after shrinking past index 4 2 6

Return 6.

Max Consecutive Ones III LeetCode Solution

Variable-size window with at most k zeros.

Max Consecutive Ones III Code
1var longestOnes = function(nums, k) {
2 let left = 0, zeros = 0, best = 0;
3 for (let right = 0; right < nums.length; right++) {
4 if (nums[right] === 0) zeros++;
5 while (zeros > k) {
6 if (nums[left] === 0) zeros--;
7 left++;
8 }
9 best = Math.max(best, right - left + 1);
10 }
11 return best;
12};

Max Consecutive Ones III in Python, Java, C++, TypeScript and C

Max Consecutive Ones III in Python
class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        left = zeros = best = 0
        for right, x in enumerate(nums):
            if x == 0:
                zeros += 1
            while zeros > k:
                if nums[left] == 0:
                    zeros -= 1
                left += 1
            best = max(best, right - left + 1)
        return best
Max Consecutive Ones III in Java
class Solution {
    public int longestOnes(int[] nums, int k) {
        int left = 0, zeros = 0, best = 0;
        for (int right = 0; right < nums.length; right++) {
            if (nums[right] == 0) zeros++;
            while (zeros > k) {
                if (nums[left] == 0) zeros--;
                left++;
            }
            best = Math.max(best, right - left + 1);
        }
        return best;
    }
}
Max Consecutive Ones III in C++
class Solution {
public:
    int longestOnes(vector<int>& nums, int k) {
        int left = 0, zeros = 0, best = 0;
        for (int right = 0; right < (int)nums.size(); right++) {
            if (nums[right] == 0) zeros++;
            while (zeros > k) {
                if (nums[left] == 0) zeros--;
                left++;
            }
            best = max(best, right - left + 1);
        }
        return best;
    }
};
Max Consecutive Ones III in TypeScript
function longestOnes(nums: number[], k: number): number {
    let left = 0, zeros = 0, best = 0;
    for (let right = 0; right < nums.length; right++) {
        if (nums[right] === 0) zeros++;
        while (zeros > k) {
            if (nums[left] === 0) zeros--;
            left++;
        }
        best = Math.max(best, right - left + 1);
    }
    return best;
}
Max Consecutive Ones III in C
int longestOnes(int* nums, int numsSize, int k) {
    int left = 0, zeros = 0, best = 0;
    for (int right = 0; right < numsSize; right++) {
        if (nums[right] == 0) zeros++;
        while (zeros > k) {
            if (nums[left] == 0) zeros--;
            left++;
        }
        if (right - left + 1 > best) best = right - left + 1;
    }
    return best;
}

Edge Cases & Common Mistakes

  • k = 0: the answer is the longest existing run of 1s.
  • k ≥ number of zeros: the whole array works.
  • All zeros: the answer is min(k, n).
  • Actually flipping the array: unnecessary; counting zeros in the window is enough.
  • Recording before shrinking: only record once zeros ≤ k.

Summary

Flipping at most k zeros means finding the longest window with at most k zeros. Grow the window on the right, shrink from the left whenever the zero count passes k, and record the longest valid window. O(n) time, O(1) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Grow on the right

    For each right, count nums[right] if it is a zero.

  2. Shrink while there are too many zeros

    While zeros > k, move left forward, decreasing the count when a zero leaves.

  3. Record the length

    The window is now valid; keep the largest right − left + 1.

Frequently asked questions

Why does flipping k zeros become a window problem?

After flipping, the answer is some contiguous block of all 1s. That block is exactly a window of the original array with at most k zeros in it. So the question becomes: what is the longest window containing at most k zeros?


Why shrink only until one zero leaves?

The window became invalid by gaining one zero too many. Moving left forward until a single zero drops out restores the limit, and any further shrinking would only make the window shorter.


What does k = 0 do?

No flips are allowed, so the window can never hold a zero, and the answer is the longest existing run of 1s, the same as Max Consecutive Ones.

New to the technique behind this problem? Watch it run step by step:

Sliding Window Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description