Maximize Sum Of Array After K Negations Problem
Description
LeetCode Problem 1005.
Given an integer array nums and an integer k, modify the array in the following way:
- choose an index
iand replacenums[i]with-nums[i].
You should apply this process exactly k times. You may choose the same index i multiple times.
Return the largest possible sum of the array after modifying it in this way.
Example 1:
Input: nums = [4,2,3], k = 1
Output: 5
Explanation: Choose index 1 and nums becomes [4,-2,3].
Example 2:
Input: nums = [3,-1,0,2], k = 3
Output: 6
Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].
Example 3:
Input: nums = [2,-3,-1,5,-4], k = 2
Output: 13
Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].
Constraints:
1 <= nums.length <= 10^4-100 <= nums[i] <= 1001 <= k <= 10^4
Solution
Approach: Greedy with Counting
To make the sum as large as possible, each flip should turn the most negative number we have into a positive one, since that gains 2 * |x|, the most we can gain. So we flip negatives from the smallest upwards until we run out of negatives or of flips.
If flips are left over, all numbers are now >= 0:
- If the number of remaining flips is even, flip any number back and forth: the sum does not change.
- If it is odd and there is a
0, spend them all on the0. - If it is odd and there is no
0, one flip has to hurt: flip the smallest positive number once, losing2 * xfor the smallestx. Note that this smallest positive may be a number that was negative a moment ago (in[-1, -1, 2]withk = 3, it is one of the 1s).
Values are between -100 and 100, so instead of sorting we count how many times each value occurs and walk the values from -100 upwards, moving counts from x to -x in bulk.
Complexity: O(n + C) time and O(C) extra space, where C = 201 is the number of possible values.
class Solution:
def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
cnt = [0] * 201 # cnt[x + 100] = how many times x occurs (-100 <= x <= 100)
for x in nums:
cnt[x + 100] += 1
# Flip negatives, most negative first.
for x in range(-100, 0):
if k == 0:
break
m = min(cnt[x + 100], k)
cnt[x + 100] -= m
cnt[-x + 100] += m
k -= m
# An odd number of flips is left and no 0 to absorb them: flip the smallest positive once.
if k % 2 == 1 and cnt[100] == 0:
for x in range(1, 101):
if cnt[x + 100]:
cnt[x + 100] -= 1
cnt[-x + 100] += 1
break
return sum((i - 100) * c for i, c in enumerate(cnt))