1005. Maximize Sum Of Array After K Negations LeetCode Solution
In this guide, you will get 1005. Maximize Sum Of Array After K Negations LeetCode Solution with the best time and space complexity. The solution to Maximize Sum Of Array After K Negations problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximize Sum Of Array After K Negations solution in C++
- Maximize Sum Of Array After K Negations solution in Java
- Maximize Sum Of Array After K Negations solution in Python
- Additional Resources

Problem Statement of 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 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.
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
Complexity Analysis
- Time Complexity: O(\texttt{sort})
- Space Complexity: O(1)
1005. Maximize Sum Of Array After K Negations LeetCode Solution in C++
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
ranges::sort(nums);
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > 0 || k == 0)
break;
nums[i] = -nums[i];
--k;
}
return accumulate(nums.begin(), nums.end(), 0) -
(k % 2) * ranges::min(nums) * 2;
}
};
/* code provided by PROGIEZ */
1005. Maximize Sum Of Array After K Negations LeetCode Solution in Java
class Solution {
public int largestSumAfterKNegations(int[] nums, int k) {
Arrays.sort(nums);
for (int i = 0; i < nums.length; ++i) {
if (nums[i] > 0 || k == 0)
break;
nums[i] = -nums[i];
--k;
}
return Arrays.stream(nums).sum() - (k % 2) * Arrays.stream(nums).min().getAsInt() * 2;
}
}
// code provided by PROGIEZ
1005. Maximize Sum Of Array After K Negations LeetCode Solution in Python
class Solution:
def largestSumAfterKNegations(self, nums: list[int], k: int) -> int:
nums.sort()
for i, num in enumerate(nums):
if num > 0 or k == 0:
break
nums[i] = -num
k -= 1
return sum(nums) - (k % 2) * min(nums) * 2
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.