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
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 index enters once and leaves once. |
| Memory | O(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