#C8355. Maximum Sum of M Elements
Maximum Sum of M Elements
Maximum Sum of M Elements
You are given a list of N integers. Your task is to select exactly M integers from this list so that their sum is maximized. This problem requires you to carefully choose a subset of the integers that yields the highest possible sum. Note that the integers can be negative, zero, or positive.
Mathematical Formulation:
Let \( a_1, a_2, \ldots, a_N \) be the given integers. You need to choose a subset \( S \) such that \(|S| = M\) and maximize the sum \[ \text{Sum}(S) = \sum_{i \in S} a_i \] with the constraint \[ |S| = M. \]
Input is provided via standard input and output should be printed to standard output.
inputFormat
The input consists of two lines:
- The first line contains two integers,
N
andM
, where1 \leq M \leq N
. - The second line contains
N
space-separated integers.
You should read input from standard input.
outputFormat
Output a single integer, which is the maximum sum obtainable by selecting exactly M
integers from the list.
The output should be printed to standard output.
## sample5 3
1 2 5 -1 4
11