![]() |
VOOZH | about |
Given an array of size n and an integer k. We must modify array k number of times. In each modification, we can replace any array element arr[i] by -arr[i]. The task is to perform this operation in such a way that after k operations, the sum of the array is maximum.
Examples :
Input : arr[] = [-2, 0, 5, -1, 2], k = 4
Output: 10
Explanation:
1. Replace (-2) by -(-2), array becomes [2, 0, 5, -1, 2]
2. Replace (-1) by -(-1), array becomes [2, 0, 5, 1, 2]
3. Replace (0) by -(0), array becomes [2, 0, 5, 1, 2]
4. Replace (0) by -(0), array becomes [2, 0, 5, 1, 2]Input : arr[] = [9, 8, 8, 5], k = 3
Output: 20
Explanation: Negate 5 three times. Array will become [9, 8, 8, -5].
Table of Content
The idea is to convert the smallest negative numbers (or smallest positive numbers if all are positive) to their opposite values.
Step by step approach:
10
Step by step approach:
10
We insert all items in a priority queue (or min heap) and then extract items one by one. The detailed approach is similar to above. Instead of sorting, we use a priority queue here.
Step by step approach: