#C11882. Maximum Sum of Contiguous Subarray of Fixed Length
Maximum Sum of Contiguous Subarray of Fixed Length
Maximum Sum of Contiguous Subarray of Fixed Length
You are given an array of integers and a positive integer \(k\). Your task is to find the maximum sum of any contiguous subarray of length \(k\). If the input is invalid (for example, when \(k\) is non-positive or larger than the array length), then the output should be 0.
For example, if the array is [2, 1, 5, 1, 3, 2] and \(k = 3\), the contiguous subarrays of length 3 are [2, 1, 5], [1, 5, 1], [5, 1, 3], and [1, 3, 2] with sums 8, 7, 9, and 6 respectively. Hence, the answer is 9.
inputFormat
The input is read from standard input (stdin) and consists of three parts:
- The first line contains an integer \(n\), representing the number of elements in the array.
- The second line contains \(n\) space-separated integers, representing the array elements.
- The third line contains an integer \(k\), which specifies the length of the contiguous subarray.
outputFormat
Output a single integer to standard output (stdout): the maximum sum of any contiguous subarray of length \(k\). If the input is invalid (i.e., if \(n = 0\), \(k \leq 0\) or \(k > n\)), output 0.
## sample6
2 1 5 1 3 2
3
9