Back to Dashboard

Max Consecutive Ones III

Hard

Problem Statement

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

Examples

Example 1:

  • Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
  • Output: 6

Approach 1 Sliding Window:

 class Solution {
    public int longestOnes(int[] nums, int k) {
      var windowStart = 0;
      var maxConsecutiveOnes = 0;
      var maxLength = 0;
      var freq = new int[2];
      for (int windowEnd = 0; windowEnd < nums.length; windowEnd ++) {
        freq[nums[windowEnd]] += 1;
        while (freq[0] > k) {
            freq[nums[windowStart]] -= 1;
            windowStart ++;
        }
        maxLength = Math.max(windowEnd - windowStart + 1, maxLength);
      }
      return maxLength;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

ArraySliding Window

Date

2026-02-16
View Problem Source