Maximum Sum of a Fixed-Size Window

Hard ⏱ 18 min 38% acceptance ★★★★★ 4.8
Write max_window_sum(numbers, k) that returns the maximum sum of any k consecutive elements in numbers, using a sliding window so the whole list is scanned only once (not recomputing the sum from scratch for every window). Assume 1 <= k <= len(numbers).

Examples

Example 1
Input
numbers = [2, 1, 5, 1, 3, 2], k = 3
Output
9
Explanation

The window [5, 1, 3] sums to 9, the largest of any 3 consecutive elements.

Constraints

  • 1 <= k <= len(numbers) <= 10^5

Topics

ListsSliding Window

Companies

AmazonMicrosoft

Hints

Hint 1

Compute the sum of the first window, then slide: subtract the element leaving, add the element entering.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.