Step 12 of 12 · Sliding windows
Maximum window sum
Problem
Read a list of whole numbers and a window size k. Return the largest sum among all contiguous groups of exactly k values.
Input
The first line contains n and k. The second line contains n space-separated integers, where 1 ≤ k ≤ n.
Output
One integer: the largest sum of any contiguous window of size k.
Examples
6 3 2 1 5 1 3 2
9
The window 5 1 3 has the largest sum, 9.
4 2 -5 -2 -8 -1
-7
The first two values form the least-negative window sum.