Algorithm
Problem Name: 1005. Maximize Sum Of Array After K Negations
Given an integer array nums
and an integer k
, modify the array in the following way:
- choose an index
i
and 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 <= 104
-100 <= nums[i] <= 100
1 <= k <= 104
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
PriorityQueue pq = new PriorityQueue<>();
int sum = 0;
for (int num : nums) {
pq.add(num);
sum += num;
}
while (k-- > 0) {
sum -= pq.peek();
sum += -1 * pq.peek();
pq.add(-1 * pq.poll());
}
return sum;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const largestSumAfterKNegations = function(A, K) {
if (A.length === 0) return 0;
A.sort((a, b) => a - b);
let res = 0;
let posIdx;
for (let i = 0, num = 0; i < A.length; i++) {
if (num < K) {
if (A[i] < 0) {
A[i] = -A[i];
} else {
if (posIdx == null) {
posIdx = Math.abs(A[i]) - Math.abs(A[i - 1]) > 0 ? i - 1 : i;
}
A[posIdx] = -A[posIdx];
}
num++;
}
}
res = A.reduce((ac, el) => ac + el, 0);
return res;
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
heapq.heapify(A)
for _ in range(K):
val = heapq.heappop(A)
heapq.heappush(A, -val)
return sum(A)
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System.Collections.Generic;
using System.Linq;
namespace LeetCode
{
public class _1005_MaximizeSumOfArrayAfterKNegations
{
public int LargestSumAfterKNegations(int[] A, int K)
{
var list = new SortedList < int, int>(A.Length);
var sum = 0;
foreach (var num in A)
{
if (!list.ContainsKey(num))
list.Add(num, 1);
else
list[num]++;
sum += num;
}
for (int i = 0; i < K; i++)
{
var num = list.First().Key;
if (num == 0) break;
sum -= num * 2;
list[num]--;
if (list[num] == 0)
list.Remove(num);
if (!list.ContainsKey(-num))
list.Add(-num, 1);
else
list[-num]++;
}
return sum;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output