Max Consecutive Ones III - Problem

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 zeros to ones.

You need to find the longest contiguous subarray that contains only 1's after flipping at most k zeros.

Example: If nums = [1,1,1,0,0,0,1,1,1,1,0] and k = 2, you can flip 2 zeros to get a maximum of 6 consecutive ones.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
💡 Note: We can flip the two zeros at indices 3 and 4 to get [1,1,1,1,1,0,1,1,1,1,0]. The longest sequence of 1's is from index 0 to 5, which has length 6.
Example 2 — All Ones
$ 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
💡 Note: We can flip 3 zeros to create the longest consecutive sequence. The optimal flips give us a sequence of length 10.
Example 3 — Edge Case
$ Input: nums = [1,1,1,1], k = 0
Output: 4
💡 Note: No zeros to flip needed. The entire array is already all 1's, so the answer is 4.

Constraints

  • 1 ≤ nums.length ≤ 105
  • nums[i] is either 0 or 1
  • 0 ≤ k ≤ nums.length

Visualization

Tap to expand
Max Consecutive Ones III: Find Longest SequenceInput: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 211100011110Sliding Window: Contains exactly k=2 zerosOptimal window from index 0 to 5 (length 6)Can flip 2 zeros at positions 3,4 to get 6 consecutive 1sOutput: 6 (maximum consecutive ones after flipping)
Understanding the Visualization
1
Input Array
Binary array with 0s and 1s, k flip budget
2
Sliding Window
Find optimal window with ≤ k zeros
3
Maximum Length
Return length of longest valid window
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently find the longest subarray with at most k zeros
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
87.6K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen