34代码随想录训练营day34|贪心算法part03

1、K次取反后最大化的数组和

K次取反后最大化的数组和

class Solution {
public:
    static bool comp(int a, int b) {
        return abs(a) > abs(b);
    }
    int largestSumAfterKNegations(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end(), comp);
        int result = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] < 0 && k > 0) {
                nums[i] *= -1;
                k--;
            }
            if (i != nums.size() - 1) result += nums[i];
        }
        if (k % 2 == 1) nums[nums.size() - 1] *= -1;
        result += nums[nums.size() - 1];
        return result;
    }
};

2、加油站

加油站

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int totalSum = 0;
        int curSnm = 0;
        int start = 0;
        for (int i = 0; i < gas.size(); i++) {
            curSnm += gas[i] - cost[i];
            totalSum += gas[i] - cost[i];
            if (curSnm < 0) {
                curSnm = 0;
                start = i + 1;
            }
        }
        if (totalSum < 0) return -1;
        return start;
    }
};

3、分发糖果

分发糖果

class Solution {
public:
    int candy(vector<int>& ratings) {
        vector<int> can(ratings.size(), 1);
        int result = 0;
        for (int i = 1; i < ratings.size(); i++) {
            if (ratings[i] > ratings[i - 1]) {
                can[i] = can[i - 1] + 1;
            }
        }
        for (int i = ratings.size() - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) {
                can[i] = max(can[i], can[i + 1] + 1);
            }
            result += can[i];
        }
        result += can.back();
        return result;
     }
};

你可能感兴趣的:(代码随想录训练营,贪心算法,算法,leetcode,c++)