#K84597. Maximum Sum Subarray of Fixed Length

    ID: 36454 Type: Default 1000ms 256MiB

Maximum Sum Subarray of Fixed Length

Maximum Sum Subarray of Fixed Length

Given an array of integers and a positive integer k, your task is to find the maximum sum obtainable from any contiguous subarray of length k. Formally, if the array is represented as \(a_0, a_1, \dots, a_{n-1}\), you need to compute the maximum value of \(\sum_{j=i}^{i+k-1}a_j\) for all valid indices \(i\) such that \(i+k-1 < n\). If k is less than or equal to 0, or if the array contains fewer than k elements, the answer is defined to be 0.

inputFormat

The input consists of two lines:

  • The first line contains two integers n and k separated by a space, where n is the number of elements in the array and k is the length of the subarray.
  • The second line contains n integers separated by spaces representing the array elements.

outputFormat

Output a single integer representing the maximum sum of any contiguous subarray of length k. If no valid subarray exists, output 0.

## sample
9 4
1 4 2 10 23 3 1 0 20
39