A shop recorded its sales for several days. Find the best stretch of k days in a row.
What to build
A program that finds the largest sum of k consecutive numbers.
Requirements
- Print the largest sum over all windows of exactly k consecutive numbers.
- Slide the window in O(n) instead of adding k numbers again each time.
Input
The first line has n and k. The second line has the n integers.
Output
The largest window sum.
Constraints
1 ≤ k ≤ n ≤ 10⁵; numbers between -10⁴ and 10⁴.
Example
Input:
6 3
2 1 5 1 3 2
Output:
9
Why it works
Moving a window one step changes its sum by one added number and one removed number, so each window costs O(1) after the first, and the whole pass is O(n).
Examples
6 3 2 1 5 1 3 2
9
5 2 -1 -2 -3 -4 -5
-3
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Compute the sum of the first k numbers once.
Hint 2
To slide one step, add the number that enters and subtract the number that leaves.
Hint 3
Keep the largest sum seen. Negative numbers are possible.
Solution
Show one correct solution (try it yourself first)
n, k = map(int, input().split())
nums = list(map(int, input().split()))
window = sum(nums[:k])
best = window
for i in range(k, n):
window += nums[i] - nums[i - k]
best = max(best, window)
print(best)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step