We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Max Consecutive Ones III

Number: 1046

Difficulty: Medium

Paid? No

Companies: Meta, LinkedIn, Google, Amazon, Microsoft, TikTok, Salesforce, Yandex, Bloomberg, Oracle, Goldman Sachs, Roku, tcs, Yahoo, Snap, SAP, Walmart Labs


Problem Description

Given a binary array nums and an integer k, the task is to determine the maximum number of consecutive 1's in the array after flipping at most k zeros to 1's.


Key Insights

  • The problem can be solved efficiently using the sliding window technique.
  • Maintain a window that can contain at most k zeros.
  • When the number of zeros in the window exceeds k, move the left pointer to shrink the window.
  • Record the maximum window length during the iteration which gives the maximum consecutive ones.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the array, since we process each element at most once. Space Complexity: O(1), only constant extra space is used.


Solution

We use a sliding window approach:

  1. Use two pointers (left and right) that define the current window.
  2. Traverse the array using the right pointer.
  3. Count the number of zeros encountered in the current window.
  4. When the count exceeds k, increment the left pointer until there are at most k zeros in the window.
  5. Throughout the process, the length of the current valid window is recorded, and the maximum window length is updated.
  6. The maximum window length gives the maximum number of consecutive 1's achievable with at most k flips.

Code Solutions

# Python solution with line-by-line comments
def longestOnes(nums, k):
    # Initialize two pointers for the sliding window and zero_count to count zeros in the window.
    left = 0
    max_length = 0
    zero_count = 0
    
    # Expand the window using the right pointer
    for right in range(len(nums)):
        # If the right element is 0, increment the zero counter
        if nums[right] == 0:
            zero_count += 1
        
        # If there are more than k zeros, shrink the window from the left
        while zero_count > k:
            if nums[left] == 0:
                zero_count -= 1
            left += 1
        
        # Update the maximum length with the current window size
        max_length = max(max_length, right - left + 1)
    
    return max_length

# Example usage:
# print(longestOnes([1,1,1,0,0,0,1,1,1,1,0], 2))
← Back to All Questions