# 1005. Maximize Sum Of Array After K Negations
LeetCode problem link (opens new window)
Given an integer array A, you can perform the following operation K times at most: Choose any index i, and replace A[i] with -A[i]. Return the maximum possible sum of the array after modifying it in this way.
Example 1:
- Input:
A = [4,2,3],K = 1 - Output: 5
- Explanation: Choose index (1), then
Abecomes [4, -2, 3].
Example 2:
- Input:
A = [3,-1,0,2],K = 3 - Output: 6
- Explanation: Choose index (1, 2, 2), then
Abecomes [3, 1, 0, 2].
Example 3:
- Input:
A = [2,-3,-1,5,-4],K = 2 - Output: 13
- Explanation: Choose index (1, 4), then
Abecomes [2, 3, -1, 5, 4].
Constraints:
- 1 <=
A.length<= 10000 - 1 <=
K<= 10000 - -100 <=
A[i]<= 100
# Approach
The approach to this problem is straightforward. How can we maximize the sum of the array?
Using a greedy strategy, find the local optimal: converting negative numbers with larger absolute values into positives maximizes the current number, leading to a global optimal solution maximizing the entire array.
The local optimal converts to a global optimal.
If all negative numbers are converted and K is still greater than zero, we now face a sequence of positive integers. How can we perform K flips on positive integers to maximize the sum?
Once again, a greedy strategy: local optimal is achieved by flipping the smallest positive number to maximize the current sum (for instance, among {5, 3, 1}, flipping 1 to -1 results in a higher number than flipping 5 to -5), resulting in the global optimal of a maximum array sum.
Even though you might easily solve this problem without considering what a greedy algorithm is, it's essential to realize that this problem involves two separate greedy strategies!
By adopting a mindset for greedy strategies (local optimal, global optimal), it becomes easier to handle both simple and difficult greedy algorithm problems.
Important to note: A thoughtful approach is crucial for solving this problem effectively.
Thus, the steps to solve this problem are:
- Step 1: Sort the array in descending order by absolute value. Ensure it's sorted by absolute value.
- Step 2: Traverse from the front, flipping negative numbers to positive while decreasing
K. - Step 3: If
Kremains greater than zero, repeatedly flip the smallest element to use upK. - Step 4: Calculate the sum.
Here is the corresponding code in C++:
class Solution {
static bool cmp(int a, int b) {
return abs(a) > abs(b);
}
public:
int largestSumAfterKNegations(vector<int>& A, int K) {
sort(A.begin(), A.end(), cmp); // Step 1
for (int i = 0; i < A.size(); i++) { // Step 2
if (A[i] < 0 && K > 0) {
A[i] *= -1;
K--;
}
}
if (K % 2 == 1) A[A.size() - 1] *= -1; // Step 3
int result = 0;
for (int a : A) result += a; // Step 4
return result;
}
};
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- Time complexity: O(nlogn)
- Space complexity: O(1)
# Conclusion
When confronted with simple greedy problems, you may think it's just common sense and question if it's indeed an algorithm. Remember, recognizing the greedy approach is critical!
Developing a mindset for solving problems with a greedy approach is always beneficial.
# Other Language Versions
# Java
class Solution {
public int largestSumAfterKNegations(int[] nums, int K) {
// Sorting the array by absolute value in descending order.
nums = IntStream.of(nums)
.boxed()
.sorted((o1, o2) -> Math.abs(o2) - Math.abs(o1))
.mapToInt(Integer::intValue).toArray();
int len = nums.length;
for (int i = 0; i < len; i++) {
if (nums[i] < 0 && K > 0) {
nums[i] = -nums[i];
K--;
}
}
// If K is greater than 0, keep flipping the smallest positive element till K is zero.
if (K % 2 == 1) nums[len - 1] = -nums[len - 1];
return Arrays.stream(nums).sum();
}
}
// Second Version: Sort the array and greedily negate negative numbers into positives as much as possible, then adjust the smallest negative or positive integer according to remaining K to attain the maximal total sum.
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
if (nums.length == 1) return nums[0];
// Sort: Initially deal with negative numbers.
Arrays.sort(nums);
for (int i = 0; i < nums.length && k > 0; i++) { // Greedily flips to use as much k by converting negative values to positive ones.
if (nums[i] < 0) {
nums[i] = -nums[i];
k--;
}
}
// Exit the loop with k > 0 || k < 0 (discussion not required if k is used up)
if (k % 2 == 1) { // k > 0 && k is odd: Flip the smallest remaining negative number or smallest positive integer.
Arrays.sort(nums); // Again sort the array to get the smallest remaining negative or smallest positive integer.
nums[0] = -nums[0];
}
// k > 0 && k is even: Flipping does not affect as flipping twice will result in the same number: For negative: - => + => -; For positive: + => - => +
int sum = 0;
for (int num : nums) { // Calculate the maximal sum
sum += num;
}
return sum;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Python
Greedy Approach
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
A.sort(key=lambda x: abs(x), reverse=True) # Step 1: Sort the array in descending order by absolute value.
for i in range(len(A)): # Step 2: Execute K negation operations
if A[i] < 0 and K > 0:
A[i] *= -1
K -= 1
if K % 2 == 1: # Step 3: If K is still available, flip the smallest absolute value element.
A[-1] *= -1
result = sum(A) # Step 4: Calculate the sum of array A
return result
2
3
4
5
6
7
8
9
10
11
12
13
14
# Go
func largestSumAfterKNegations(nums []int, K int) int {
sort.Slice(nums, func(i, j int) bool {
return math.Abs(float64(nums[i])) > math.Abs(float64(nums[j]))
})
for i := 0; i < len(nums); i++ {
if K > 0 && nums[i] < 0 {
nums[i] = -nums[i]
K--
}
}
if K%2 == 1 {
nums[len(nums)-1] = -nums[len(nums)-1]
}
result := 0
for i := 0; i < len(nums); i++ {
result += nums[i]
}
return result
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# JavaScript
var largestSumAfterKNegations = function(nums, k) {
nums.sort((a,b) => Math.abs(b) - Math.abs(a))
for(let i = 0 ;i < nums.length; i++){
if(nums[i] < 0 && k > 0){
nums[i] = - nums[i];
k--;
}
}
// If k is still greater than 0, find the smallest number and keep flipping it.
while( k > 0 ){
nums[nums.length-1] = - nums[nums.length-1]
k--;
}
// Use of arrow function's implicit return - if using written shorthand, remove brackets, else include return before a + b.
return nums.reduce((a, b) => a + b)
};
// Second version (optimized: one pass)
var largestSumAfterKNegations = function(nums, k) {
nums.sort((a, b) => Math.abs(b) - Math.abs(a)); // Sorting
let sum = 0;
for(let i = 0; i < nums.length; i++) {
if(nums[i] < 0 && k-- > 0) { // Greedy approach, flip negative to positive as much as possible
nums[i] = -nums[i];
}
sum += nums[i]; // Sum calculation
}
if(k % 2 > 0) { // Remaining k (>0 & odd): k flips result to a negative
sum -= 2 * nums[nums.length - 1]; // Subtract twice the smallest value (added once already)
}
return sum;
};
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Rust
impl Solution {
pub fn largest_sum_after_k_negations(mut nums: Vec<i32>, mut k: i32) -> i32 {
nums.sort_by_key(|b| std::cmp::Reverse(b.abs()));
for v in nums.iter_mut() {
if *v < 0 && k > 0 {
*v *= -1;
k -= 1;
}
}
if k % 2 == 1 {
*nums.last_mut().unwrap() *= -1;
}
nums.iter().sum()
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# C
#define abs(a) (((a) > 0) ? (a) : (-(a)))
// Sum of the array
int sum(int *nums, int numsSize) {
int sum = 0;
int i;
for(i = 0; i < numsSize; ++i) {
sum += nums[i];
}
return sum;
}
int cmp(const void* v1, const void* v2) {
return abs(*(int*)v2) - abs(*(int*)v1);
}
int largestSumAfterKNegations(int* nums, int numsSize, int k){
qsort(nums, numsSize, sizeof(int), cmp);
int i;
for(i = 0; i < numsSize; ++i) {
// Traverse the array, if the current element < 0, flip it, reduce k by 1
if(nums[i] < 0 && k > 0) {
nums[i] *= -1;
--k;
}
}
// If there are remaining k after traversing, the smallest absolute element nums[numsSize - 1] is flipped.
if(k % 2 == 1)
nums[numsSize - 1] *= -1;
return sum(nums, numsSize);
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# TypeScript
function largestSumAfterKNegations(nums: number[], k: number): number {
nums.sort((a, b) => Math.abs(b) - Math.abs(a));
let curIndex: number = 0;
const length = nums.length;
while (curIndex < length && k > 0) {
if (nums[curIndex] < 0) {
nums[curIndex] *= -1;
k--;
}
curIndex++;
}
while (k > 0) {
nums[length - 1] *= -1;
k--;
}
return nums.reduce((pre, cur) => pre + cur, 0);
};
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Scala
object Solution {
def largestSumAfterKNegations(nums: Array[Int], k: Int): Int = {
var num = nums.sortWith(math.abs(_) > math.abs(_))
var kk = k // Because k is immutable, assign it to a mutable variable
for (i <- num.indices) {
if (num(i) < 0 && kk > 0) {
num(i) *= -1 // Flip
kk -= 1
}
}
// If kk is odd, flip the smallest value (since it's previously added once)
if (kk % 2 == 1) num(num.size - 1) *= -1
num.sum // Return the sum of numbers
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# C#
public class Solution
{
public int LargestSumAfterKNegations(int[] nums, int k)
{
int res = 0;
Array.Sort(nums, (a, b) => Math.Abs(b) - Math.Abs(a));
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] < 0 && k > 0)
{
nums[i] *= -1;
k--;
}
}
if (k % 2 == 1) nums[nums.Length - 1] *= -1;
foreach (var item in nums) res += item;
return res;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19