Course Schedule III

There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.

Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.

Example:

Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
Output: 3
Explanation: 
There're totally 4 courses, but you can take 3 courses at most:
First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. 
Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. 
The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.

Note:
The integer 1 <= d, t, n <= 10,000.
You can’t take two courses simultaneously

From:
Leetcode-Algorithm-Greedy

Hint:
题目给出一系列课程的持续时长和截止日期,要我们找出最多能上几门课。很容易想到要把临近截止以及持续时间短的课程优先考虑。但如果只考虑其中之一,必然得不到最优解。
贪心算法必然要基于以上两部分综合考虑。
首先把所有课程按照截止日期的先后进行排序,
1: 最先考虑最临近截止日期的课程
2: 如果课程是可安排的, 就让该课程加入安排队列。
3: 如果课程是不可安排的,比较它的课程时长L0与安排队列中最长的课程(Cm)时长Lm,如果L0小于Lm, 使用这个课程替换Cm。显然这个操作不会改变原安排队列其他课程的可安排性,并且这会使总的已安排时间减少。而之前被判断不可安排的以及被踢出安排队列的课程的时长都会比当前被踢出队列的课程时长更长,因此也不会改变它们的不可安排性。因此我们每次获得的都是当前已考虑课程的最优解,最后自然能得到一个全局的最优解。
时间复杂度O(nlogn)—排序

class Solution {
public:

    int scheduleCourse(vector<vector<int>>& mycourses) {
        vector<pair<int, int> > courses;
        for (int i = 0; i < mycourses.size(); i++) {
            courses.push_back(pair<int,int>(mycourses[i][1], mycourses[i][0]));
        }
        sort(courses.begin(), courses.end());

        priority_queue<int> ans;
        int curtime = 0;
        for (auto course : courses) {
            if (course.first >= curtime+course.second) {
                ans.push(course.second);
                curtime += course.second;
            } else {
                int temp = ans.top();
                if (temp > course.second) {
                    ans.pop();
                    ans.push(course.second);
                    curtime += -temp+course.second;
                }
            }
        }
        return ans.size();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值