48. Maximum Sum Subarray of Size K
Difficulty: easy · Array, Prefix Sum
Problem
Given an array of `n` integers and an integer `k`, find the maximum sum of any contiguous subarray of exactly `k` elements.
Input
- Line 1: two integers `n` and `k`. - Line 2: `n` space-separated integers.
Output
Print the maximum sum of a window of size `k`.
Example 1
Input: 6 3 2 1 5 1 3 2 Output: 9
Explanation: The window 5 1 3 has sum 9, the largest of the four windows (8, 7, 9, 6).
Example 2
Input: 4 2 -1 -2 -3 -4 Output: -3
Explanation: All windows are negative; -1 + -2 = -3 is the largest.
Constraints
- 1 <= k <= n <= 10^5 - -10^9 <= arr[i] <= 10^9
Solutions are judged against 2 sample and 9 hidden tests. Sign in to solve it · All problems