← All coding problems
Maximum Sum of K Consecutive Elements
easyPlacement Coding+10 XPTime limit 2s
Find the largest sum of any k consecutive elements of the array.
Input:
- line 1:
n k - line 2:
nintegers
Output: the maximum sum.
Constraints: 1 ≤ k ≤ n ≤ 10⁵, −10⁴ ≤ values ≤ 10⁴.
Think about it: this is the classic sliding window. When the window moves one step right, add the new element and subtract the one that left — no need to re-add all k numbers.
Sample input 1
6 3 2 1 5 1 3 2
Sample output 1
9
Sample input 2
3 1 -5 -2 -9
Sample output 2
-2
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).