Problem 205
Maximum Sum Subarray of Size K
Easy · 10 pts · Array, Sliding Window
Problem
You are given an array of N integers and a window size K. Among all blocks of exactly K consecutive elements, find the one with the largest sum, and print that sum. Use a sliding window: compute the sum of the first K elements, then move the window one step at a time, adding the element that enters on the right and subtracting the element that leaves on the left. This takes O(N) instead of O(N × K).
Input
First line: integers N and K. Second line: N space-separated integers.
Output
Print the maximum window sum.
Constraints
1 <= K <= N <= 100000; -10000 <= A[i] <= 10000
Example input
6 3 2 1 5 1 3 2
Example output
9
Explanation
The windows of size 3 in 2 1 5 1 3 2 have sums 8 (2 1 5), 7 (1 5 1), 9 (5 1 3) and 6 (1 3 2). The largest is 9.