Course Schedule III — LeetCode 630 Python Solution
- Problem
- #630
- Pattern
- Heap / Priority Queue
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi.
Example
- Input
- courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]
- Output
- 3
- Explanation
- There are totally 4 courses, but you can take 3 courses at most:
Python solution
class Solution:
def scheduleCourse(self, courses: List[List[int]]) -> int:
courses.sort(key=lambda x: x[1])
pq = []
s = 0
for duration, last in courses:
heappush(pq, -duration)
s += duration
while s > last:
s += heappop(pq)
return len(pq)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(1) to O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 630. Course Schedule III is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 630. Course Schedule III?
- LeetCode 630. Course Schedule III is rated Hard on LeetCode.
- What topics does LeetCode 630. Course Schedule III cover?
- LeetCode 630. Course Schedule III is tagged Greedy, Array, Sorting and Heap (Priority Queue) on LeetCode.