Maximum Sum of a Fixed-Size Subarray
EasyPractice library · +10 XPsliding windowarraysprefix sums
Given an array of N integers and an integer k, find the contiguous subarray of size k that has the largest sum. Print this maximum sum.
Input
The first line contains two integers N and k, separated by a space. The second line contains N integers, the elements of the array.
Output
Print a single integer representing the maximum sum of a subarray of size k.
Constraints
1 <= k <= N <= 1000. The array elements are integers between -1000 and 1000.
Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests
Example 1
Input
5 3 2 1 5 1 3
Output
9
The subarrays of size 3 are [2, 1, 5], [1, 5, 1], and [5, 1, 3]. Their sums are 8, 7, and 9 respectively. The maximum sum is 9.
Example 2
Input
4 2 -1 -2 -3 -4
Output
-3
The subarrays of size 2 are [-1, -2], [-2, -3], and [-3, -4]. Their sums are -3, -5, and -7. The maximum sum is -3.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
5 3 2 1 5 1 3
Example 2 input
4 2 -1 -2 -3 -4