Max Consecutive Ones III

Updated on 06 June, 2025
Max Consecutive Ones III header image

Problem Statement

In this problem, you are given a binary array nums where each element is either 0 or 1. The problem also provides an integer k, which represents the maximum number of elements in the array that can be flipped from 0 to 1. Your objective is to determine the maximum length of a subarray (a contiguous section of the array) that contains only 1s after making no more than k flips from 0 to 1.

Examples

Example 1

Input:

nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2

Output:

6

Explanation:

By flipping two 0s at positions 4 and 5, the subarray [1,1,1,1,1,1] is formed.

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

Explanation:

Flipping three 0s allows the longest subarray of 10 continuous 1s to form.

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1
  • 0 <= k <= nums.length

Approach and Intuition

The goal is to find the length of the longest subarray containing only 1s after flipping at most k zeroes. A highly efficient way to solve this is by using the sliding window technique:

  1. Initialize two pointers, start and end, to define the window bounds.

  2. Use a counter zero_count to track how many 0s are in the current window.

  3. Expand the window by moving end forward.

    • If nums[end] is 0, increment zero_count.
    • If zero_count exceeds k, shrink the window from the left by moving start forward until the number of zeroes is <= k.
  4. At every step, compute the window size (end - start + 1) and update the maximum length seen so far.

This method ensures:

  • All subarrays considered contain at most k zeroes.
  • Each element is visited at most twice: once by end and once by start.

As a result, the algorithm runs in O(n) time, where n is the length of the input array — well within the problem’s constraints.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int maxConsecutiveOnes(vector<int>& arr, int maxFlips) {
        int start = 0, end;
        int len = arr.size();
        for (end = 0; end < len; end++) {
            if (arr[end] == 0) {
                maxFlips--;
            }
            if (maxFlips < 0) {
                maxFlips += 1 - arr[start];
                start++;
            }
        }
        return end - start;
    }
};

This solution involves optimizing the length of the longest subarray that consists of consecutive 1's. This is possible by flipping a limited number of 0's to 1's, specified by maxFlips. The implementation utilizes a sliding window approach to efficiently find the maximum length of such a subarray in a given array arr.

Here's a breakdown of the approach:

  • Initialize two pointers, start and end, which represent the current window of numbers under consideration.
  • Iterate over the array using the end pointer, expanding the window to include new elements from arr.
  • If the current element is 0, decrement maxFlips to account for flipping this zero to one.
  • If maxFlips becomes negative, it indicates that more than the allowed number of flips have been used. Adjust the start pointer to shrink the window from the left until maxFlips is non-negative again. This ensures that the window only contains a valid number of flips.
  • The maximum length of the window that satisfies the condition is updated continuously by calculating the difference between the end and start pointers.
  • At the end of the loop, the length of the longest valid subarray is returned as end - start.

This code highlights efficient use of the sliding window technique to maintain a dynamically adjusting subarray that fulfills the flip condition, thus finding the answer in linear time relative to the size of arr.

java
class Solution {
    public int maxConsecutiveOnes(int[] arr, int flips) {
        int start = 0, end;
        for (end = 0; end < arr.length; end++) {
            if (arr[end] == 0) {
                flips--;
            }
            if (flips < 0) {
                flips += 1 - arr[start];
                start++;
            }
        }
        return end - start;
    }
}

To tackle the problem "Max Consecutive Ones III" in Java, follow these steps:

  • Define the method maxConsecutiveOnes accepting an integer array arr and an integer flips, where arr represents a binary array and flips denotes the maximum number of 0s that can be flipped to 1s.
  • Initialize two integer variables start and end to zero. start will track the beginning of the window, while end will extend the current window of consecutive ones.
  • Iterate through the array using end as the index for accessing each element in the array:
    • If the current element arr[end] at the index end is 0, decrement flips as flipping a 0 to a 1 is considered.
    • If flips becomes negative (indicating more flips than allowed), adjust the window from the start:
      • Increment flips by 1 if the element at the start index is 0 (1 - arr[start] does this adjustment).
      • Increment start to effectively reduce the window size, moving past the element that caused the extra flip.
  • Finally, calculate the maximum number of consecutive ones attainable by subtracting start from end. Since all elements have been checked when the loop concludes, end - start gives the length of the longest segment with at most flips flipped zeros.

This logic efficiently expands and contracts a sliding window over the array to determine the maximum length of consecutive ones, including up to a specified number of zeros that could be flipped, culminating in the determination of the desired length.

python
class Solution:
    def maxConsecutiveOnes(self, data: List[int], flips: int) -> int:
        start = 0
        for end in range(len(data)):
            flips -= 1 - data[end]
            if flips < 0:
                flips += 1 - data[start]
                start += 1
        return end - start + 1

The provided Python code implements a solution that efficiently finds the maximum length of consecutive ones in a binary array after flipping at most flips zero values to ones. This task is addressed using a sliding window technique, optimized to handle arrays and integer operations effectively. Here's how the code works:

  1. Initialize start to zero, marking the beginning of a sliding window.
  2. Iterate over the array using end as the index. The window is extended from start to end.
  3. Decrease the flips count each time a zero is encountered in the window.
  4. If flips becomes negative (indicating that more than flips zeros have been flipped to sustain the current window), increment start to shrink the window from the beginning and correct the flips balance—restoring flips only if a zero is passed over by the start pointer.
  5. Calculate the length of the current window (end - start + 1) to update the potential maximum whenever necessary.

The code returns the maximum number of consecutive ones that can be obtained by flipping up to flips zeros. This approach is efficient and handles edge cases with minimal computational overhead, leveraging linear time complexity relative to the size of the input array, thus providing a robust solution for large datasets.

Comments

No comments yet.