#C9918. Maximum Subsequence Sum with Limited Elements

    ID: 54064 Type: Default 1000ms 256MiB

Maximum Subsequence Sum with Limited Elements

Maximum Subsequence Sum with Limited Elements

In this problem, you are given an array of integers and a number (K). Your task is to select at most (K) elements from the array such that the sum of these elements is maximized. Note that if (K = 0) then the answer is defined to be 0, and if (K) is greater than the number of elements in the array, you should sum all the elements. The solution is based on the observation that the maximum sum is obtained by choosing the largest (K) elements in the array. Formally, if the sorted array in descending order is (a_1, a_2, \dots, a_N), then the answer is (\sum_{i=1}^{\min(K,N)} a_i) (with the convention that an empty sum is 0).

inputFormat

The first line contains two integers (N) and (K) (where (N) is the number of array elements and (K) is the maximum number of elements that can be selected). The second line contains (N) space-separated integers representing the array elements.

outputFormat

Output a single integer which is the maximum sum achievable by selecting at most (K) elements from the array.## sample

4 2
1 2 3 4
7

</p>