#K94817. Maximum Sum Subarray of Fixed Length
Maximum Sum Subarray of Fixed Length
Maximum Sum Subarray of Fixed Length
Given an array of integers and an integer k, your task is to find the largest sum of any contiguous subarray of length exactly k. If k > n (where n is the length of the array), print -1.
You can compute the sum of any subarray with indices from i to i+k-1 using the formula:
\( S = \sum_{j=i}^{i+k-1} a_j \)
If no valid subarray exists, output -1
.
inputFormat
The first line contains two space-separated integers n and k, where n is the number of elements in the array and k is the fixed length of the subarray.
The second line contains n space-separated integers representing the elements of the array.
Note: Input is provided via stdin
.
outputFormat
Output a single integer which is the maximum sum of any contiguous subarray of length k. If no such subarray exists, output -1
.
The result should be printed to stdout
.
6 3
2 1 5 1 3 2
9