题目链接:https://leetcode-cn.com/problems/maximize-sum-of-array-after-k-negations/
题目描述:
题解:
1.按绝对值从大到小排序
2.遍历整个数组,遇到负数,将负数变正数
3.如果遍历完整个数组,K仍然大于0,将数组的最后一个值取反。K为偶数,则为原数值,k为奇数,则为原数的相反数。
class Solution { public: static bool compare(int a, int b) { return abs(a) > abs(b); } int largestSumAfterKNegations(vector<int>& nums, int k) { int result = 0; sort(nums.begin(), nums.end(), compare); for(int i = 0; i < nums.size() - 1; i++) { if(k > 0 && nums[i] < 0) { nums[i] = abs(nums[i]); k--; } } if(k % 2 == 1) nums[nums.size() - 1] *= -1; for(int a : nums) result += a; return result; } };