Maximize Sum Of Array After K Negations - Problem

Given an integer array nums and an integer k, modify the array in the following way: choose an index i and replace nums[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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,2,3], k = 1
Output: 5
💡 Note: Choose index 1 and nums becomes [4,-2,3]. Sum is 4 + (-2) + 3 = 5, which is the maximum possible.
Example 2 — Multiple Negations
$ Input: nums = [3,-1,0,2], k = 3
Output: 6
💡 Note: Choose indices (1, 2, 2) and nums becomes [3,1,0,2]. Sum is 3 + 1 + 0 + 2 = 6.
Example 3 — All Negative
$ Input: nums = [-1,-2,-3], k = 2
Output: 4
💡 Note: Flip the two most negative: [-1,-2,-3] → [-1,-2,3] → [-1,2,3]. Sum is -1 + 2 + 3 = 4.

Constraints

  • 1 ≤ nums.length ≤ 104
  • -100 ≤ nums[i] ≤ 100
  • 1 ≤ k ≤ 104

Visualization

Tap to expand
Maximize Sum: [4,2,3] with k=1 negation423Input ArrayChoose smallest element (2)to minimize loss when negated4-23After 1 negationMaximum Sum: 4 + (-2) + 3 = 5Strategy: Negate smallest positive to minimize loss
Understanding the Visualization
1
Input
Array [4,2,3] with k=1 operations allowed
2
Process
Choose optimal element to negate for maximum sum
3
Output
Maximum possible sum after k negations
Key Takeaway
🎯 Key Insight: Always flip the most negative numbers first, or if all positive, flip the smallest to minimize loss
Asked in
Google 15 Amazon 12
28.3K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen