VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximize-array-sum-after-k-negations-using-sorting/

⇱ Maximize array sum after K negations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximize array sum after K negations

Last Updated : 3 May, 2026

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].

[Naive Approach] Repeatedly Negate Minimum - O(n * k) time and O(1) space

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:

  1. Iterate k times to perform the allowed modifications. In each iteration,
    • find the index of the minimum element
    • Negate the element at the found minimum index
    • Repeat the process for k iterations
  2. Return the total sum of the modified array

Output
10

[Expected Approach 1] Using Sorting - O(n Log n) time and O(1) space

Step by step approach:

  1. Sort the array in ascending order.
  2. Convert negative numbers to positive until k modifications are used or all negative numbers are negated.
  3. Handle remaining modifications by checking if k is even or odd. We can perform modification on the same element even times, so we do not have to change any value. So set k = k%2.
  4. If k is odd, subtract twice the minimum element from the sum. We subtract two times in order to first remove the minimum value from sum and then add the negated value to sum.
  5. Return the final maximized sum.

Output
10

[Expected Approach 2] Priority Queue - O(n Log n) time and O(n) space

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:

  1. Create a min-heap and insert all array elements into it.
  2. Perform k operations by repeatedly extracting the minimum element.
  3. Negate the minimum element and reinsert it back into the heap.
  4. After k operations, calculate the sum of all elements in the heap.


Comment
Article Tags: