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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code