Course Schedule III

HardGreedyLeetCode 630 ↗World 7-7
0:00 / 0:00

Take the most courses before their deadlines: sort by deadline, keep a max-heap of durations, and drop the longest when time runs over.

▼

The problem

LeetCode 630 (Hard). courses[i] = [duration, lastDay]: course i takes duration days and must be finished by day lastDay. You take courses one at a time, starting on day 1. Return the maximum number of courses you can take. (This is not the graph Course Schedule: ../course-schedule and ../course-schedule-ii are topological sorts; this one is about deadlines, and the title card says so.)

Example (new in the remake, chosen so the drop matters): [[3,10],[5,5],[2,13],[4,7],[2,6]] → 4 (everything but the five-day course: in deadline order 2, 4, 3, 2 end on days 2, 6, 9, 11, each before its due day).

TRY IT ON LEETCODE ▶

The solution

import heapq

def scheduleCourse(courses):
    courses.sort(key=lambda c: c[1])
    heap, time = [], 0
    for dur, last in courses:
        heapq.heappush(heap, -dur)   # max heap
        time += dur
        if time > last:
            time += heapq.heappop(heap)  # minus the longest
    return len(heap)

Transcript

Course Schedule Three. Not prerequisites this time: deadlines. Each course takes some days and has a last day. Starting on day one, you take one course at a time. What's the most you can finish?

Five courses: three days due by day ten, five due by day five, two due by day thirteen, four due by day seven, and two due by day six. The best is four: everything but the five-day course.

The brute force tries every subset in deadline order and checks that each one ends in time: two to the n subsets, times n. Five courses make thirty-two. Forty make over a trillion.

Instead, sort by deadline and take each course in turn. The five-day course ends on day five, just in time. The two-day course would end on day seven, past its deadline of six. You could skip it. Better: drop the longest course taken, the five-day one. Still one course, but the clock is back at day two.

A max heap finds the longest course fast. And one drop is always enough: the dropped course is at least as long as the new one, so the time falls back to where it was, or earlier.

Let's walk it. Five days: day five, on time. Two days: day seven, late, so drop the five, back to day two. Four days: day six, before seven. Three days: day nine, before ten. Two days: day eleven, before thirteen. Four courses. Skipping instead would have finished only three.

In code, sort by last day. For each course, push its duration and add it to the time. If the time passes the last day, pop the longest and subtract it. The heap's size is the answer.

Sorting is n log n, and each push or pop is log n: order n log n time, and order n space.

Sort by deadline, take every course, drop the longest when you're late. That's Course Schedule Three.