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 - Sliding Window INPUT nums array (11 elements) 1 1 1 0 0 0 1 1 1 1 0 indices: 0 1 2 3 4 5 6 7 8 9 10 Input Values nums = [1,1,1,0,0,0,1,1,1,1,0] k = 2 (max flips allowed) = 1 (one) = 0 (zero) Goal: Find longest subarray with at most k zeros ALGORITHM STEPS 1 Initialize Pointers left=0, right=0, zeroCount=0 2 Expand Right Move right, count zeros 3 Shrink if Needed If zeros > k, move left 4 Track Maximum maxLen = max(right-left+1) Optimal Window Found: 0 0 1 1 1 1 indices 4-9: flip 2 zeros left=4 right=9 while zeroCount > k: if nums[left]==0: zeroCount-- left++ FINAL RESULT Longest window with at most 2 zeros: 1 1 1 0 0 0 1 1 1 1 0 indices 4 to 9 (length = 6) OUTPUT 6 OK - Verified! Window [4,9]: 2 zeros flipped Result: 6 consecutive 1s Time: O(n) Space: O(1) Key Insight: The sliding window technique maintains a window with at most k zeros. When zeros exceed k, shrink from left until valid. This achieves O(n) time as each element is visited at most twice (once by right pointer expanding, once by left pointer shrinking). TutorialsPoint - Max Consecutive Ones III | Sliding Window Approach
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