#K4961. Maximum Sum of K Consecutive Elements

    ID: 28681 Type: Default 1000ms 256MiB

Maximum Sum of K Consecutive Elements

Maximum Sum of K Consecutive Elements

You are given an array of n integers and an integer k. Your task is to compute the maximum sum of any k consecutive elements in the array.

More formally, for an array a with indices ranging from 0 to n-1, you need to find:

$$S = \max_{0 \leq i \leq n-k}\left\{ \sum_{j=i}^{i+k-1} a_j \right\} $$

If the array is empty or if k is greater than n, output 0.

This is a classical sliding window problem that can be solved efficiently by maintaining the sum of the current window and updating it as the window slides over the array.

inputFormat

The input is read from standard input (stdin) and consists of two lines:

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

outputFormat

The output is written to standard output (stdout) and should be a single integer representing the maximum sum of any k consecutive elements in the array.

## sample
5 2
1 2 3 4 5
9