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.
课程表III。题意是给一个array of array,里面存放的是一些课程的[花费时间,关门时间]。其中关门时间的意思是超过这个时间,你就不能修这门课程。请问在时间允许范围内你最多能修几门课。例子,
输入: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
输出: 3
解释:
这里一共有 4 门课程, 但是你最多可以修 3 门:
首先, 修第一门课时, 它要耗费 100 天,你会在第 100 天完成, 在第 101 天准备下门课。
第二, 修第三门课时, 它会耗费 1000 天,所以你将在第 1100 天的时候完成它, 以及在第 1101 天开始准备下门课程。
第三, 修第二门课时, 它会耗时 200 天,所以你将会在第 1300 天时完成它。
第四门课现在不能修,因为你将会在第 3300 天完成它,这已经超出了关闭日期。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/course-schedule-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是贪心。这个题几乎跟前两个版本没什么关系,因为并没有用到拓扑排序的知识。这道题的思路是,首先对所有课程按关门时间从小到大排序,因为这里的贪心是需要看看是否能尽快修完关门时间比较靠前的课。再创建一个优先队列(priority queue)构造的最大堆,把每个课程的花费时间放入。这样先弹出的永远是耗费时间长的课程。创建一个变量time记录已经花费的时间,然后开始遍历input数组。
如果time + course[0] <= course[1]说明已花费时间 + 当前课程的花费时间 <= 当前课程的关门时间,则将这门课的花费时间加入最大堆;如果time + course[0] > course[1]说明当前这门课是没法修的,这时弹出堆顶元素,因为对顶元素是耗时最长的课。弹出这门课,当前的课就一定能上。
时间O(nlogn) - sort, pq的操作
空间O(n) - priority queue
Java实现
1 class Solution { 2 public int scheduleCourse(int[][] courses) { 3 Arrays.sort(courses, (a, b) -> a[1] - b[1]); 4 PriorityQueuequeue = new PriorityQueue<>((a, b) -> b - a); 5 int time = 0; 6 for (int i = 0; i < courses.length; i++) { 7 time += courses[i][0]; 8 queue.offer(courses[i][0]); 9 if (time > courses[i][1]) { 10 time -= queue.poll(); 11 } 12 } 13 return queue.size(); 14 } 15 }
LeetCode 题目总结