U

41. Maximum Sum Subarray of Fixed Length K

Med.

Problem Description

Given an array of NN integers and an integer KK (1≤K≤N1 \le K \le N), find the maximum sum of any contiguous subarray of length exactly KK.

Input Format

  • •Line 1: Two space-separated integers NN and KK.
  • •Line 2: NN space-separated integers A1,…,ANA_1, \dots, A_N.

Output Format

Print the maximum sum of a length-KK contiguous subarray.

Example 1:
Input:
5 3
1 4 2 10 23
Output:
35
Explanation: Subarray [2, 10, 23] has maximum sum 2 + 10 + 23 = 35.
Example 2:
Input:
4 1
-1 -2 -3 -4
Output:
-1
Explanation: Window size 1; maximum single element is -1.
Example 3:
Input:
3 3
10 20 30
Output:
60
Explanation: Entire array sum is 60.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online