Full answer
Problem
Given nums and k, return the largest sum of k consecutive elements.
Example: daily sales [2, 1, 5, 1, 3, 2], k = 3 gives 9 (days 2 to 4: 5 + 1 + 3).
Constraints: 1 <= k <= len(nums) <= 10^5; values may be negative. Invalid k raises ValueError.
Brute force
For each start index, sum the next k values: O(n x k). With n = 10^5 and k = 5 x 10^4 that is billions of additions.
Optimal approach
window = sum(nums[:k]),best = window.- For
ifrom k to n - 1:window += nums[i] - nums[i - k], then updatebest.
Why it works
Two neighbouring windows share k - 1 elements. Moving from window [i - k, i - 1] to [i - k + 1, i] drops exactly nums[i - k] and adds exactly nums[i], so the running total is always the correct sum of the current window.
Complexity
O(n) time, O(1) space.
Code
def max_sum_window(nums, k):
"""Largest sum of any k consecutive values. Fixed-size sliding window, O(n)."""
if k <= 0 or k > len(nums):
raise ValueError("need 1 <= k <= len(nums)")
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k] # add the new day, drop the oldest
best = max(best, window)
return best
if __name__ == "__main__":
assert max_sum_window([2, 1, 5, 1, 3, 2], 3) == 9
assert max_sum_window([4, 2, 1, 7, 8, 1, 2, 8, 1, 0], 3) == 16
assert max_sum_window([5], 1) == 5
assert max_sum_window([-4, -2, -7], 2) == -6
assert max_sum_window([1, 2, 3], 3) == 6
for bad_k in (0, 4):
try:
max_sum_window([1, 2, 3], bad_k)
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")Save as a21_max_sum_window.py and run python3 a21_max_sum_window.py. It prints all tests passed (Python 3.13.5).
Edge cases
k == len(nums) (one window). k == 1 (the maximum element). All negative values (the best is the least negative window, so do not initialise best to 0). k outside 1..n is rejected.
Pattern
Fixed-size sliding window: maintain an aggregate as the window moves by one. The same template computes moving averages, counts of vowels in every window, and anagram checks with letter counts.
def max_sum_window(nums, k):
"""Largest sum of any k consecutive values. Fixed-size sliding window, O(n)."""
if k <= 0 or k > len(nums):
raise ValueError("need 1 <= k <= len(nums)")
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k] # add the new day, drop the oldest
best = max(best, window)
return best
if __name__ == "__main__":
assert max_sum_window([2, 1, 5, 1, 3, 2], 3) == 9
assert max_sum_window([4, 2, 1, 7, 8, 1, 2, 8, 1, 0], 3) == 16
assert max_sum_window([5], 1) == 5
assert max_sum_window([-4, -2, -7], 2) == -6
assert max_sum_window([1, 2, 3], 3) == 6
for bad_k in (0, 4):
try:
max_sum_window([1, 2, 3], bad_k)
raise AssertionError("expected ValueError")
except ValueError:
pass
print("all tests passed")Fixed window with an O(1) update per step; rejects k outside 1..len(nums).
Complexity
Time: O(n). Space: O(1). The brute force that re-sums each window is O(n * k).
By level
Fresher: Writes the brute force, then the sliding update, and traces the sales example. Should state O(n) time and O(1) space.
Mid: Handles negatives and invalid k cleanly and contrasts fixed windows with variable windows. Tests a window equal to the whole list.
Senior: Generalises to streaming moving aggregates, discusses numeric precision for floating-point averages and when a deque is needed for window maximum. Explains when a prefix sum array is a better fit for many queries.
Key points
- Neighbouring windows share k - 1 elements
- Update by adding the new element and subtracting the old one
- Initialise best from the first window, not 0
- O(n) time, O(1) space
- Validate k
Common mistakes
- Re-summing every window
- Initialising best to 0 with negative inputs
- Off-by-one on the index that leaves the window
- Not handling k larger than the list
Follow-ups
- How would you compute the average of every window?
- What if you need the maximum element of each window instead of the sum?
- What if the window size can vary?
Tips
- Explain the shared-elements idea in one sentence
- Trace two slides on the example
- Test with negative numbers
Evaluation rubric
- Correct O(n) algorithm
- Correct initialisation
- Handles invalid k
- States complexity