Leetcode 9.11每日一题 630. 课程表 III

这里有 n 门不同的在线课程,按从 1 到 n 编号。给你一个数组 courses ,其中 courses[i] = [durationi, lastDayi] 表示第 i 门课将会 持续 上 durationi 天课,并且必须在不晚于 lastDayi 的时候完成。

你的学期从第 1 天开始。且不能同时修读两门及两门以上的课程。

返回你最多可以修读的课程数目。

示例 1:

输入:courses = [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
输出:3
解释:
这里一共有 4 门课程,但是你最多可以修 3 门:
首先,修第 1 门课,耗费 100 天,在第 100 天完成,在第 101 天开始下门课。
第二,修第 3 门课,耗费 1000 天,在第 1100 天完成,在第 1101 天开始下门课程。
第三,修第 2 门课,耗时 200 天,在第 1300 天完成。
第 4 门课现在不能修,因为将会在第 3300 天完成它,这已经超出了关闭日期。

示例 2:

输入:courses = [[1,2]]
输出:1

示例 3:

输入:courses = [[3,2],[4,3]]
输出:0

提示:

  • 1 <= courses.length <= 104
  • 1 <= durationi, lastDayi <= 104

思路:最优选应当是时间最迟并且当前课所花费时间最少,因此,对课的最迟时间进行升序排序,然后一次累加时间,当累加的时间大于当前的最迟时间,开始考虑已读取的时间中花费最多的时间与当前所需时间进行比较,取最小值

class Solution {
public:
    int scheduleCourse(vector>& courses) {
        sort(courses.begin(), courses.end(),[](const vector& a, const vector& b) {
            return a[1] < b[1];
        });
        priority_queue q;
        int total = 0;
        for(auto& course : courses) {
            int t = course[0], d = course[1];
            if(total + t <= d) {
                total += t;
                q.push(t);
            }else {
                if(!q.empty() && q.top() > t) {
                    total -= q.top() - t;
                    q.pop();
                    q.push(t);
                }
            }
        }
        return q.size();
    }
};

 

你可能感兴趣的:(leetcode,算法,数据结构,c++)