AAlgoLoopSpaced repetition for LeetCode
MEDIUMSliding WindowLeetCode ↗

Max Consecutive Ones III

The key idea

Find the longest subarray that contains at most k zeros. Slide a window: expand the right edge always, and shrink the left edge only when the window holds more than k zeros. The largest window width ever seen is the answer.

Problem

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

Constraints

Examples

Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 Output: 6
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

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Sliding Window problems