Problem 475849 · easy · Level 04 Non-Linear Data Structures

Flip Signs to Maximise the Total

heaps · greedy · min-heap

You are given a list of integers nums and an integer k. You must perform exactly k sign flips: each flip picks one element and multiplies it by -1. The same element may be flipped more than once. Return the largest possible sum of the list after the k flips.

Examples

Input:  nums = [6, 3, 8], k = 3
Output: 11
Explanation: every element is positive, so all three flips land on the smallest: 3 -> -3 -> 3 -> -3,
             giving 6 - 3 + 8.

Input:  nums = [5, 0, -3, 9, 1], k = 4
Output: 18
Explanation: flip -3 to 3, then spend the remaining three flips on the 0. Sum 5 + 0 + 3 + 9 + 1.

Input:  nums = [-7, 2, -4, -1, 6, -9], k = 2
Output: 19
Explanation: flip -9 and -7: 7 + 2 - 4 - 1 + 6 + 9.

Constraints

  • 1 <= len(nums) <= 10**5, -10**4 <= nums[i] <= 10**4
  • 1 <= k <= 10**5
  • Target complexity: O(n + k log n).

Goals

  • Recognise that the best value to negate is always the current minimum
  • Apply exactly k operations even when they stop being useful
  • Use heapreplace to pop and push in one step
Starting Python…