~/problems / Sliding window

Basics: best sum of k in a row (fixed-size window)

easy basics ~10 min

Write max_window_sum(nums: list[int], k: int) -> int that returns the largest sum of any k consecutive elements of nums.

max_window_sum([4, -1, 2, 7, -5, 3], 3)   # 8    (-1 + 2 + 7)
max_window_sum([-3, -8, -2], 1)           # -2
  • 1 <= k <= len(nums) <= 2 * 10^5; values are in [-10^4, 10^4] and can be negative.
  • Re-summing each window with sum(nums[i:i + k]) is O(n·k). The tests include n = 200,000 and k = 50,000, where that takes far too long. Aim for O(n).
Show hint

when the window slides one step right, its sum changes by exactly two numbers: add the one entering, nums[i], and subtract the one leaving, nums[i - k].

Topic: Sliding window. Grow right, shrink left while invalid; monotonic deque for window max/min.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc