1005.K次取反后最大化的数组和
链接地址
class Solution {
private:static bool cmp(int a , int b) {return abs(a) > abs(b);}
public:int largestSumAfterKNegations(vector<int>& nums, int k) {//第一步排序sort(nums.begin(), nums.end(),cmp);//第二步for (int i = 0; i < nums.size(); i++) {if (nums[i] < 0 && k > 0) {nums[i] *= -1;k--;}}//如果k是偶数直接给最小的值附一个负号if (k % 2 == 1) nums[nums.size() - 1] *= -1;int result = 0;for (int x : nums) {result += x;}return result;}
};