1047. Maximize Sum Of Array After K Negations
My accepted C++ solution to LeetCode problem 1047, Maximize Sum Of Array After K Negations, running in 0ms.
- Difficulty: Easy
- C++
- Runtime 0ms
- Memory 12.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
C++
Accepted on LeetCode — runtime 0ms, memory 12.6MB, accepted 2025-12-27.
class Solution {
public:
int largestSumAfterKNegations(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() && k > 0 && nums[i] < 0; i++, k--) {
nums[i] = -nums[i];
}
int minVal = *min_element(nums.begin(), nums.end());
int sum = accumulate(nums.begin(), nums.end(), 0);
return k % 2 == 0 ? sum : sum - 2 * minVal;
}
};