Maximize array sum after K negations
Pattern: Candy and assign cookies
Sort, then flip negatives from the most negative upwards while flips remain. If flips are left over, all values are now at least 0: an even number cancels out, and an odd number is spent on the smallest value.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Negate exactly k times (any index, the same index more than once allowed) and return the largest possible sum.
[3, -1, 0, 2] with k = 3 gives 6. The catalogue has no practice link for this one. LeetCode's Maximize Sum Of Array After K Negations is the same task.
Think first
- Which flip gains the most?
- When no negatives are left, what happens to extra flips?
- Which value should take a leftover odd flip?
Hints
Brute force, and why it fails
Try every sequence of k indexes: nᵏ.
The key insight
Flips help most on the most negative values; once all are non-negative, only the parity of what is left matters.
Dry run
| k | 2 |
|---|
nums = [3, -1, 0, 2], k = 3. Sorted: -1, 0, 2, 3. Flip -1: k = 2.
The plan
sort; for i while k > 0 and a[i] < 0: a[i] = -a[i]; k -= 1
return sum(a) - (2 × min(a) if k is odd else 0)
Complexity
- Time
O(n log n)- Space
O(n)
Sorting dominates.
Edge cases
- A 0 in the array absorbs any odd leftover for free.
- k larger than the number of negatives.
- All positive.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
int[] a = nums.clone();
Arrays.sort(a);
for (int i = 0; i < a.length && k > 0 && a[i] < 0; i++, k--) a[i] = -a[i]; // flip the most negative first
int sum = 0, smallest = Integer.MAX_VALUE;
for (int x : a) {
sum += x;
smallest = Math.min(smallest, x);
}
return k % 2 == 1 ? sum - 2 * smallest : sum; // an odd number of flips left: spend them on the smallest
}
}C++
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
vector<int> a(nums);
sort(a.begin(), a.end());
for (size_t i = 0; i < a.size() && k > 0 && a[i] < 0; i++, k--) a[i] = -a[i]; // flip the most negative first
int sum = 0, smallest = INT_MAX;
for (int x : a) {
sum += x;
smallest = min(smallest, x);
}
return k % 2 == 1 ? sum - 2 * smallest : sum; // an odd number of flips left: spend them on the smallest
}
};Python
class Solution:
def largestSumAfterKNegations(self, nums: list[int], k: int) -> int:
a = sorted(nums)
for i in range(len(a)):
if k == 0 or a[i] >= 0:
break
a[i] = -a[i] # flip the most negative first
k -= 1
return sum(a) - (2 * min(a) if k % 2 else 0) # an odd number of flips left: spend them on the smallestCommon mistakes
- Taking
minbefore the flips instead of after. - Flipping positives while negatives remain.