Sliding Window · Variable size

Max Consecutive Ones Visualizer

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

Try every startFrom each index, flip zeros until the budget runs out. Those overlapping scans repeat the same zeros.
A window with a flip budgetCount zeros as the right edge grows. When the count passes k, move the left edge until a zero leaves.

Interactive solution

Ones and zeros, with the flip count under the window
for each new bit:
if it is 0, use one flip
while flips exceed k, move L forward
best = max(best, length)
return best
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each bit enters and leaves once.
MemoryO(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