#C9677. Maximum Sum of a k-Length Subarray

    ID: 53796 Type: Default 1000ms 256MiB

Maximum Sum of a k-Length Subarray

Maximum Sum of a k-Length Subarray

Given n flowers with various heights, you are allowed to rearrange them in any order. Your task is to determine the maximum possible sum of any contiguous subarray of length k after an optimal rearrangement.

This problem can be formulated as follows: you are given an array \(A\) of length \(n\) and an integer \(k\) (with \(1 \leq k \leq n\)). You are allowed to permute the elements of \(A\) arbitrarily. The maximal sum you can obtain by summing any contiguous block of \(k\) elements is achieved by placing the \(k\) largest numbers consecutively. In mathematical notation, if \(A\) is sorted in non-decreasing order and \(A_{1}, A_{2}, \ldots, A_{n}\) are its elements, then the answer is given by:

$$ \sum_{i=1}^{k} A_{n-i+1} $$

inputFormat

The first line of input contains two integers (n) and (k) (with (1 \leq k \leq n)), representing the number of flowers and the length of the subarray, respectively. The second line contains (n) space-separated integers which denote the heights of the flowers.

outputFormat

Output a single integer representing the maximum sum of a contiguous subarray of length (k) after optimally rearranging the flowers.## sample

5 3
1 3 2 5 4
12

</p>