代码随想录训练营day29|贪心算法part3

加油站

力扣题目链接

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int pre = 0;
        int cur;
        int result = 0;
        int sumGas = 0;
        for(int i = 0; i < gas.size(); i++){
            sumGas = sumGas + gas[i] - cost[i];
            cur = gas[i] - cost[i];
            // 存在一个点能到达之后的所有点
            if(pre <= 0 && cur > 0){
                result = i;
                pre = 0;
            }
            pre = pre + gas[i] - cost[i];
        }
        // 能跑完全程
        return (sumGas >= 0) ? result : -1;
    }
};

分发糖果

力扣题目链接

class Solution {
public:
    int candy(vector<int>& ratings) {
        vector<int> candy(ratings.size(), 1);
        // 左右各遍历一次
        for(int i = 1; i < ratings.size(); i++){
            if(ratings[i] > ratings[i-1])
                candy[i] = candy[i-1] + 1;
        }
        for(int i = ratings.size()-2; i >= 0; i--){
            if(ratings[i] > ratings[i+1]){
                candy[i] = max(candy[i+1] + 1, candy[i]);
            }
        }
        int result = 0;
        for(int i : candy){
            result += i;
        }   
        return result;
    }
};

柠檬水找零

力扣题目链接

class Solution {
public:
    bool lemonadeChange(vector<int>& bills) {
        int num5 = 0;
        int num10 = 0;
        for(int i : bills){
            if(i == 5)
                num5++;
            else if(i == 10){
                num10++;
                num5--;
            }
            else if(i == 20 && num10 > 0){
                num10--;
                num5--;
            }
            else if(i == 20 && num10 == 0){
                num5 -= 3;
            }
            if(num5 < 0 || num10 < 0)
                return false;
        }
        return true;
    }
};

根据身高重建队列

力扣题目链接

class Solution {
public:
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
        // 高度降序,一样高时,k升序
        sort(people.begin(), people.end(), [](vector<int>& a, vector<int>& b){
            if(a[0] == b[0])
                return a[1] < b[1];
            return a[0] > b[0];
        });
        vector<vector<int>> result;
        // 后插入的不影响先插入的项
        for(int i = 0; i < people.size(); i++){
            result.insert(result.begin() + people[i][1], people[i]);
        }
        return result;
    }
};

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