HardNo. 0630

Course Schedule III — LeetCode 630 Python Solution

Topics
Greedy, Array, Sorting, Heap (Priority Queue)
Reading time
3 min

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

PythonSolution
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

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

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

Related problems
No.ProblemDifficulty
0207Course ScheduleMedium
0502IPOHard
0857Minimum Cost to Hire K WorkersHard
1353Maximum Number of Events That Can Be AttendedMedium
1383Maximum Performance of a TeamHard
1686Stone Game VIMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.