代码随想录算法训练营第三十五天 | 1005.K次取反后最大化的数组和 134.加油站 135.分发糖果

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

题目链接 文章讲解 视频讲解

思路:
  按绝对值从大到小排序
  遍历数组,遇到负数,如果次数未用完就取反
  最后如果剩余次数未用完且为奇数就将数组最后一个元素取反

class Solution {
    static bool myCompare(const int& lhs, const int& rhs) {
        return abs(lhs) > abs(rhs);
    }
public:
    int largestSumAfterKNegations(vector<int>& nums, int k) {
        int result = 0;
        sort(nums.begin(), nums.end(), myCompare);
        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;

        for(int val : nums) result += val;
        return result;
    }
};

134.加油站

题目链接 文章讲解 视频讲解

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        // 记录最后剩余的油量
        int totalSum = 0;
        // 记录当前剩余的油量
        int curSum = 0;
        int startIndex = 0;
        for(int i = 0; i < gas.size(); ++i) {
            curSum += (gas[i] - cost[i]);
            totalSum += (gas[i] - cost[i]);
            // 如果当前剩余油量为负数,那么从下一个位置开始重新记录
            if(curSum < 0) {
                startIndex = i + 1;
                curSum = 0;
            }
        }
        if(totalSum < 0) return -1;
        return startIndex;
    }
};

135.分发糖果

题目链接 文章讲解 视频讲解

思路:
  先从左向右遍历,如果当前孩子的分数相较于前者高,则糖果数为前者加一
  如果没有前者高则默认为1
  再从后向前遍历,如果当前孩子得分比后者高,则再当前糖果和后者糖果加一的糖果数中取更大的一个
  同时累加总的糖果数

class Solution {
public:
    int candy(vector<int>& ratings) {
        int total = 0;
        vector<int> candys(ratings.size(), 1);
        // 从前向后遍历,保证比左边的孩子得分高者符合要求
        for(int i = 1; i < ratings.size(); ++i) {
            if(ratings[i] > ratings[i - 1]) {
                candys[i] = candys[i - 1] + 1;
            }
        }
        total += candys[ratings.size() - 1];
        // 从右向左遍历,保证比右边孩子得分高者符合要求
        for(int i = ratings.size() - 2; i >= 0; --i) {
            if(ratings[i] > ratings[i + 1]) candys[i] = max(candys[i], candys[i + 1] + 1);
            total += candys[i];
        }
        return total;
    }
};
posted @ 2024-06-10 20:51  深蓝von  阅读(4)  评论(0编辑  收藏  举报