←
Lens · Sliding Window · Fixed size

Maximum sum of k numbers in a row

20
11
52
13
34
25
window
–
best
–
k
3
The goalFind the biggest sum of any 3 numbers in a row.
1 / 13

Code

O(n) time · O(1) space
1def max_sum(nums, k):2    window = sum(nums[:k])3    best = window4    for r in range(k, len(nums)):5        window += nums[r] - nums[r - k]6        best = max(best, window)7    return best
WHY IT WORKSDon't re-add k numbers every time. Add the one that enters, subtract the one that leaves.