leetcode: 1005. Maximize Sum Of Array After K Negations(贪心)

leetcode: 1005. Maximize Sum Of Array After K Negations(贪心)

原题链接

class Solution {
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) {
                k--;
                nums[i] *= -1;
            }
        }
        if (k % 2 == 1) nums[nums.size() - 1] *= -1;
        int ans = 0;
        for (int x : nums) ans += x;
        return ans; 
    }
};

你可能感兴趣的:(Leetcode,leetcode,贪心算法,算法)