Course Schedule III — LeetCode 630 Python Solution

HardGreedyArraySortingHeap (Priority Queue)
Problem
#630
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

Python
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

MeasureComplexity
TimeO(n log n)
SpaceO(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.

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.

Get Stealth Interview