代码随想录刷题第33天

第一题是k次取反后求数组最大和https://leetcode.cn/problems/maximize-sum-of-array-after-k-negations/description/,使用了两次贪心策略:第一次是优先将绝对值大的负数进行取反,若负数取完后,取反次数仍有剩余,则将小正数进行取反。

class Solution {
static bool cmp(int a, int b){
    return abs(a) > abs(b);
}
public:
    int largestSumAfterKNegations(vector& 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--;
            }
        }
        if (k % 2 == 1) nums[nums.size() - 1] *= -1;
        int result = 0;
        for (int i = 0; i < nums.size(); i++){
            result += nums[i];
        }
        return result;
    }
};

第二题是加油站https://leetcode.cn/problems/gas-station/submissions/502393587/,容易想到的思路是从各个位置开始遍历,知道找出满足要求的起始位置为止,但是代码不好写。

class Solution {
public:
    int canCompleteCircuit(vector& gas, vector& cost) {
    for (int i =0; i < cost.size(); i++){
        int rest = gas[i] - cost[i];
        int index = (i + 1) % cost.size();
        while(rest > 0 && index != i){//环形遍历用while
            rest += gas[index] - cost[index];
            index = (index + 1) % cost.size();
        }
        if (index == i && rest >= 0) return i;
    }
    return -1;
    }
};

贪心的解法是求出每一站的剩余油量并相加,如果当前遍历发现剩余油量小于0,则重新从下一站开始遍历。

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

    }
};

第三题是分发糖果https://leetcode.cn/problems/candy/description/,需要两次遍历确定当前元素与两边元素的大小关系。从前向后比较当前元素与左侧元素的大小关系,再从后向前比较当前元素与右边元素的大小关系。

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

你可能感兴趣的:(leetcode,算法,职场和发展)