|
U
Pro41. Maximum Sum Subarray of Fixed Length K
Med.
Problem Description
Given an array of N integers and an integer K (1≤K≤N), find the maximum sum of any contiguous subarray of length exactly K.
Input Format
- •Line 1: Two space-separated integers N and K.
- •Line 2: N space-separated integers A1,…,AN.
Output Format
Print the maximum sum of a length-K 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
Code
|Loading Code Editor...
SavedLn 1, Col 1
param_1 =
param_2 =
Sandboxed Engine
Ctrl+Enter = Run | Ctrl+Shift+Enter = Submit