#C4232. Maximum Sum of K Consecutive Elements

    ID: 47748 Type: Default 1000ms 256MiB

Maximum Sum of K Consecutive Elements

Maximum Sum of K Consecutive Elements

Given an array of integers and an integer k, your task is to compute the maximum sum of any k consecutive elements in the array. If the input parameters are invalid (i.e., if k ≤ 0, or k > n where n is the number of elements in the array, or if the array is empty), output 0.

This problem can be efficiently solved using the sliding window technique. The algorithm involves computing the sum of the first k elements, and then iteratively updating the sum by subtracting the element that is no longer in the window and adding the next element. The maximum of these sums is the desired result.

The mathematical formulation for a valid window is as follows:

\[ \text{max_sum} = \max_{0 \leq i \leq n-k} \left(\sum_{j=i}^{i+k-1} a_j\right) \]

inputFormat

The input is provided via standard input (stdin) in the following format:

  • The first line contains two space-separated integers: n (the number of elements in the array) and k (the number of consecutive elements to sum).
  • The second line contains n space-separated integers representing the array elements.

If n is 0, or if k ≤ 0 or k > n, the output should be 0.

outputFormat

Output a single integer to standard output (stdout) – the maximum sum of any k consecutive elements in the array. In case of invalid input conditions, output 0.

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

</p>