算法:反悔贪心

反悔贪心

课程表
这里有 n 门不同的在线课程,按从 1 到 n 编号。给你一个数组 courses ,其中 courses[i] = [durationi, lastDayi] 表示第 i 门课将会 持续 上 durationi 天课,并且必须在不晚于 lastDayi 的时候完成。你的学期从第 1 天开始。且不能同时修读两门及两门以上的课程。返回你最多可以修读的课程数目。

class Solution {
public:
    int scheduleCourse(vector<vector<int>>& courses) {
        sort(courses.begin(), courses.end(), [](const vector<int>&v1, const vector<int>&v2){
            return v1[1] < v2[1]; //按照结束时间排序
        });
        priority_queue<int> pq;
        int day = 0;
        for(int i=0;i<courses.size();i++){
            int duration = courses[i][0], last_day = courses[i][1];
            if(duration + day <= last_day){ //满足条件
                pq.push(duration);
                day += duration;
            }else if(!pq.empty() && pq.top() > duration){ //选出持续时间最长的剔除
                day += duration - pq.top();
                pq.pop();
                pq.push(duration);
            }
        }
        return pq.size();

    }
};

871. 最低加油次数

class Solution {
public:
    int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
        priority_queue<int> pq;
        sort(stations.begin(), stations.end(), [](const vector<int>&v1, const vector<int>&v2){
            return v1[0] <v2[0];//对加油站位置进行排序
        });
        int now = startFuel;
        int idx = 0;
        int n = stations.size();
        int cnt = 0;
        while(now < target){
            while(idx < n && stations[idx][0] <= now){
                pq.push(stations[idx++][1]);
            }
            if(pq.empty())return -1;
            now += pq.top();//选取最大油量进行加油
            cnt ++;
            pq.pop();
        }
        return cnt;

    }
};

LCP 30. 魔塔游戏

class Solution {
public:
    int magicTower(vector<int>& nums) {
        priority_queue<int, vector<int>, greater<>>pq;
        int cnt=0;
        long long sum=0;
        for(int i:nums)sum+=i;
        if(sum<0)return -1;
        long long now = 1;
        for(int i:nums){
            now+=i;
            if(i<0){
                pq.push(i);
            }
            if(now<=0){
                
                while(!pq.empty() && now<=0){
                    cnt++;
                    now-=pq.top();
                    pq.pop();
                }
            }
        }
        return cnt;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_43983809

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值