Ecommet

Max Consecutive Ones III

Medium Problem 25 of 151 Java and Python

Problem

Given a binary array nums and an integer k, return the maximum number of consecutive 1s in the array if you can flip at most k zeros to ones.

Example 1

Input
nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 2
Output
6
Why
Flip the zeros at indices 5 and 10 to get 1, 1, 1, 1, 1, 1 from index 5 to 10.

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

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • nums[i] is 0 or 1.
  • 0 ≤ k ≤ nums.length

Explanation

Rephrase it: find the longest subarray that contains at most k zeros. Those zeros are the ones you flip.

Grow the window on the right; whenever it holds more than k zeros, move the left edge forward until it is valid again.

Approach 1 · Naive

Every start, count zeros

  • Time O(n²)
  • Space O(1)

From each start, extend the end while the number of zeros stays within k.

  1. For each i, set zeros = 0.
  2. For j ≥ i: count zeros; stop when zeros > k; otherwise update the best with j - i + 1.
Java
class Solution {
    public int longestOnes(int[] nums, int k) {
        int best = 0;
        for (int i = 0; i < nums.length; i++) {
            int zeros = 0;
            for (int j = i; j < nums.length; j++) {
                if (nums[j] == 0) {
                    zeros++;
                }
                if (zeros > k) {
                    break;
                }
                best = Math.max(best, j - i + 1);
            }
        }
        return best;
    }
}
Python
class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        best = 0
        for i in range(len(nums)):
            zeros = 0
            for j in range(i, len(nums)):
                zeros += nums[j] == 0
                if zeros > k:
                    break
                best = max(best, j - i + 1)
        return best

Approach 2 · Optimal

Window with at most k zeros

  • Time O(n)
  • Space O(1)

Count zeros inside the window. Shrink from the left while there are too many, and record the window length after each step.

  1. Set left = 0, zeros = 0.
  2. For each right: if nums[right] == 0, increment zeros.
  3. While zeros > k: if nums[left] == 0, decrement zeros; increment left.
  4. Update the best with right - left + 1.
Java
class Solution {
    public int longestOnes(int[] nums, int k) {
        int left = 0;
        int zeros = 0;
        int 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;
    }
}
Python
class Solution:
    def longestOnes(self, nums: List[int], k: int) -> int:
        left = zeros = best = 0
        for right, num in enumerate(nums):
            zeros += num == 0
            while zeros > k:
                zeros -= nums[left] == 0
                left += 1
            best = max(best, right - left + 1)
        return best

Complexity compared

ApproachTimeSpace
Naive Every start, count zerosO(n²)O(1)
Optimal Window with at most k zerosO(n)O(1)

Key takeaways

  • Turning "flip at most k" into "window with at most k bad elements" is the key reframe.

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem