Sliding Window · Fixed size

Max Sum of Size K Visualizer

What is Max Sum of Size K

Find the contiguous block of exactly k values whose sum is largest. The window moves one step at a time: subtract the value that leaves and add the value that enters.

2 1 5 1 3 2
k = 3
9

Approach

Resum every blockAdding k values again for every start index repeats the same work. On a long array with a large k that is too slow.
Reuse the previous sumThe next block shares k - 1 values with this one. One addition and one subtraction produce the next sum.

Interactive solution

A block of length k, its sum, and the best sum
sum = first k values
best = sum
for each new index:
sum += entering - leaving
best = max(best, sum)
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 index enters once and leaves once.
MemoryO(1)Only the running sum and the best sum are stored.

Implementation

def max_sum(a, k):
    cur = sum(a[:k])
    best = cur
    for i in range(k, len(a)):
        cur += a[i] - a[i - k]
        best = max(best, cur)
    return best