[LeetCode - 贪心算法]630. Course Schedule III

1 题目

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.

2 分析

  • 能不能完成一门课与这门课的截至日期有直接关系,要上最多的课,首先要上截止日期在最前面的课。令time表示当前时间,每上一门课,就令time的值加上这门课的课时。
  • 选接下来的课程时,先参加该课程,即 time = time + duration,如果参加后本课程后,time > deadline, 就从已经选的课程中去掉占用课时最多的课程, 并更新time(注:如果课时最长的课程是本门课,那么就去掉本门课,如果不是,那么去掉最长课时的已选课程。这两种情况下,已经选择的课程不均超过其截止日期)。重复上面的步骤,直到考虑了所有的课程。

3 源码

public class Solution {
    public int scheduleCourse(int[][] courses) {
        //按照课程截至日期排序
        Arrays.sort(courses,(a,b)->{return a[1]-b[1];});
        //用最大优先级队列存储已经选择了的课程
        PriorityQueue<Integer> pq = new PriorityQueue<>((a,b)->b-a);
        int time = 0;
        for(int[] course : courses){
            time += course[0];
            pq.add(course[0]);
            //如果当前考虑的课程超期了,就从已选择的课程中去掉课时最长的
            if(time > course[1]){
                time -= pq.poll();
            }
        }
        //最终优先级队列中的课程数,就是能够选择的最多课程
        return pq.size();
    }
}
    原文作者:贪心算法
    原文地址: https://blog.csdn.net/jitianyu123/article/details/74611466
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞