What is Max Consecutive Ones
The array contains only 0 and 1. You may flip up to k zeros into ones. Return the longest stretch of ones you can build. The window stays valid while the zeros inside it are at most k.
1 1 1 0 0 0 1 1 1 1 0 k = 2 6
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each bit enters and leaves once. |
| Memory | O(1) | Only the zero count and the two ends are stored. |
Implementation
def max_ones(a, k):
l = zeros = best = 0
for r, v in enumerate(a):
if v == 0:
zeros += 1
while zeros > k:
if a[l] == 0:
zeros -= 1
l += 1
best = max(best, r - l + 1)
return best