# 630. Course Schedule III

**<font color=red>难度: Hard</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/course-schedule-iii/description/

> 内容描述

```

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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(NlgN)******- 空间复杂度: O(N)******


跟我一开始的思路很接近，但是我的代码没有这个精简

See []().

```
Sort all the courses by their ending time. When considering the first K courses, they all end before end. 
A necessary and sufficient condition for our schedule to be valid, is that (for all K),
the courses we choose to take within the first K of them, have total duration less than end.

For each K, we will greedily remove the largest-length course until the total duration start is <= end. 
To select these largest-length courses, we will use a max heap. start will maintain the loop invariant that 
it is the sum of the lengths of the courses we have currently taken.

Clearly, this greedy choice makes the number of courses used maximal for each K. 
When considering potential future K, there's never a case 
where we preferred having a longer course to a shorter one, so indeed our greedy choice dominates all other candidates.
```

beats 73.33%

```python
class Solution(object):
    def scheduleCourse(self, courses):
        """
        :type courses: List[List[int]]
        :rtype: int
        """
        start, taken = 0, []
        for duration, end in sorted(courses, key = lambda x: x[1]):
            start += duration
            heapq.heappush(taken, -duration)
            while start > end:
                start -= -heapq.heappop(taken)
        return len(taken)
```

优化了一波代码之后 beats 100%

```python
class Solution(object):
    def scheduleCourse(self, courses):
        """
        :type courses: List[List[int]]
        :rtype: int
        """
        courses, start, taken = sorted(courses, key = lambda x: x[1]), 0, []
        for course in courses:
            if start + course[0] <= course[1]:
                start += course[0]
                heapq.heappush(taken, -course[0])
            elif len(taken) > 0 and -taken[0] > course[0]:
                pop_duration = -heapq.heappop(taken)
                start = start - pop_duration + course[0]
                heapq.heappush(taken, -course[0])
        return len(taken)
```
