Problem 970
Maximize Sum Of Array After K Negations
Easy · 10 pts · Array, Greedy, Sorting
Problem
Perform exactly K operations, each choosing an index i and replacing A[i] by -A[i] (the same index may be chosen more than once). Maximise the sum of the array afterwards. Greedy: negate the most negative numbers first, in sorted order. If operations are left over and their number is odd, flip the element with the smallest absolute value once more; an even number of extra flips cancels out.
Input
The first line contains N and K. The second line contains the N integers.
Output
Print the largest possible sum.
Constraints
1 <= N <= 10000; -100 <= A[i] <= 100; 1 <= K <= 10000
Example input
3 1 4 2 3
Example output
5
Explanation
For 4 2 3 with K = 1, there is no negative number, so negate the smallest value 2: the array becomes 4 -2 3 with sum 5.