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 Of Array After K Negations INPUT nums array: 4 index 0 2 index 1 3 index 2 k = 1 Input Values: nums = [4, 2, 3] k = 1 Current sum: 9 ALGORITHM STEPS 1 Sort Array Sort to find smallest [2, 3, 4] 2 Find Min Element Smallest = 2 at idx 0 3 Negate Minimum Change 2 to -2 [-2, 3, 4] 4 Calculate Sum -2 + 3 + 4 = 5 Greedy Strategy: Negate smallest to maximize total sum 2 --> -2 (loss: -4) FINAL RESULT Modified array: -2 negated 3 4 Sum calculation: -2 + 3 + 4 Output: 5 OK - Verified Maximum sum achieved Key Insight: The greedy approach works by always negating the smallest element. For positive arrays, negate the minimum element repeatedly. For arrays with negatives, prioritize negating negative numbers to make them positive, maximizing the overall sum. TutorialsPoint - Maximize Sum Of Array After K Negations | Greedy Approach
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