代码随想录算法训练营DAY29第八章 贪心算法 part03

目录

[134. 加油站](#134. 加油站)

[135. 分发糖果](#135. 分发糖果)

[860. 柠檬水找零](#860. 柠檬水找零)

[406. 根据身高重建队列](#406. 根据身高重建队列)


134. 加油站

cpp 复制代码
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int ans=0;
        int sum=0;
        int minsum=0;
        for(int i=0;i<gas.size();i++){
            sum+=gas[i]-cost[i];
            if(sum<minsum){
                minsum=sum;
                ans=i+1;
            }
        }
        if(sum<0)return -1;
        else return ans;
    }
};

135. 分发糖果

cpp 复制代码
class Solution {
public:
    int candy(vector<int>& ratings) {
        int n=ratings.size();
        int ans=n;
        vector<int> left(n);
        for(int i=0;i<n;i++){
            if(i&&ratings[i]>ratings[i-1])left[i]=left[i-1]+1;
            else left[i]=0;
        }
        int right=0;
        for(int i=n-1;i>=0;i--){
            if(i!=n-1&&ratings[i]>ratings[i+1])right++;
            else right=0;
            ans+=max(left[i],right);
        }
        return ans;
    }
};

860. 柠檬水找零

cpp 复制代码
class Solution {
public:
    bool lemonadeChange(vector<int>& bills) {
        unordered_map<int,int> map;
        for(int t:bills){
            if(t==5)map[5]++;
            else if(t==10){
                if(map[5])map[5]--;
                else return false;
                map[10]++;
            }
            else {
                if(map[10]&&map[5]){
                    map[10]--;
                    map[5]--;
                }
                else if(map[5]>=3){
                    map[5]-=3;
                }
                else return false;
                map[20]++;
            }
        }
        return true;
    }
};

406. 根据身高重建队列

cpp 复制代码
class Solution {
    static bool com(vector<int>& a,vector<int>& b){
        if(a[0]!=b[0])return a[0]>b[0];
        else return a[1]<b[1];
    }
public:
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
        vector<vector<int>>ans;
        sort(people.begin(),people.end(),com);
        for(int i=0;i<people.size();i++){
            int k=people[i][1];
            ans.insert(ans.begin()+k,people[i]);
        }
        return ans;
    }
};
相关推荐
delishcomcn9 分钟前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹20 分钟前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术1 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
CV-Climber3 小时前
检索技术的实际应用
人工智能·算法
hhzz4 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_5 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
TsingtaoAI5 小时前
3D高斯泼溅技术发展及其在具身智能领域的应用综述
人工智能·算法·ai·具身智能·高斯泼溅
atunet5 小时前
关于图算法中的连通分量检测与最小割问题7
算法
心运软件6 小时前
银行客户流失预测(Python 完整实战)
算法