#C706. Maximum Sum of K Consecutive Elements
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 find the maximum sum of any k consecutive elements in the array.
If k is less than or equal to 0, or if k is greater than n, the result is defined to be 0.
Formally, given an array A with elements \(A_1, A_2, \ldots, A_n\), you need to compute
[ \max_{1 \leq i \leq n-k+1} \sum_{j=i}^{i+k-1} A_j ]
if (n \geq k) and (k > 0); otherwise, output 0.
This is a typical sliding window problem that can be solved in \(O(n)\) time.
inputFormat
The input is read from standard input and consists of two lines:
- The first line contains two space-separated integers:
n
(the size of the array) andk
(the number of consecutive elements to consider). - The second line contains
n
space-separated integers representing the elements of the array.
outputFormat
Output a single integer which is the maximum sum of any k
consecutive elements in the array. If k
is invalid (\(k \le 0\) or \(k > n\)), output 0.
4 2
100 200 300 400
700
</p>