Problem 630

Abstract / Summary

Choose maximum total credits by taking courses without overlapping time using start and end times.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0630.py

class Solution:
    def scheduleCourse(self, courses: List[List[int]]) -> int:
        # sort by lastday
        ordered = [ ( lastday, duration ) for duration, lastday in courses ]
        ordered.sort()

        # remove impossible courses
        while ordered and ordered[0][0] < ordered[0][1]:
            ordered.pop(0)

        # attended courses
        taken = [] # max-heap

        now = 0
        for lastday, duration in ordered:
            # try attending the course
            heappush(taken, -duration)
            now += duration
            while taken and now > lastday:
                # remove longest courses (can be the current course !)
                longest = -heappop(taken) # max-heap
                now    -= longest

        return len(taken)
24 lines | 801 bytes | submitted November 28, 2023 | GitHub   46% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 41% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Heap (Priority Queue)
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “course schedule” problem by selecting the maximum number of courses that can be completed before their respective deadlines. It follows a greedy strategy combined with a max-heap to keep the total time spent as low as possible while respecting deadline constraints. The algorithm proceeds through distinct phases: sorting the input, discarding courses that are impossible from the start, iteratively attempting to take each course, and discarding the longest taken course whenever the current schedule exceeds a deadline.

Sorting and Preparation

The first step transforms the list of [duration, lastday] pairs into a list of (lastday, duration) tuples and sorts them by deadline. This ordering guarantees that courses with earlier deadlines are considered before later ones, which is essential for the greedy approach.

ordered = [(lastday, duration) for duration, lastday in courses]
ordered.sort()

By sorting once at the beginning, the algorithm avoids repeated scans of the unsorted input and ensures that later decisions are made with a globally consistent view of deadline priorities.

Removing Impossible Courses

Before the main loop, the code eliminates any course whose duration already exceeds its deadline. Such a course can never be part of a feasible schedule, so removing it early reduces unnecessary heap operations.

while ordered and ordered[0][0] < ordered[0][1]:
    ordered.pop(0)

The loop continues until the first remaining course satisfies the basic feasibility condition, effectively pruning the input to a set of potentially viable courses.

Greedy Selection with Max-Heap

The core of the algorithm iterates over the sorted courses. For each course, it tentatively adds the course’s duration to a running total now and pushes the negative duration onto a heap named taken. Using negative values turns Python’s min-heap implementation into a max-heap, allowing quick access to the longest duration among the selected courses.

taken = []          # max-heap (implemented with negative values)
now = 0
for lastday, duration in ordered:
    heappush(taken, -duration)
    now += duration
    while taken and now > lastday:
        longest = -heappop(taken)   # remove the longest course
        now -= longest

If adding the current course causes the accumulated time now to exceed the current deadline lastday, the inner loop removes the longest course from the heap. This removal may discard the just-added course or a previously taken one, whichever has the greatest duration. By always discarding the longest duration, the algorithm minimizes the total time spent while preserving the number of courses taken.

When the inner loop finishes, the schedule up to the current deadline is feasible. The heap taken therefore always contains a set of courses that can be completed within their respective deadlines, and its size reflects the number of courses successfully scheduled so far.

Edge Cases Handled

The implementation gracefully handles several edge conditions:

  • Courses whose duration exceeds their own deadline are filtered out before any heap activity, preventing futile attempts to schedule them.
  • When multiple courses share the same deadline, the sorted order ensures they are processed together, and the heap removal logic automatically selects the optimal subset based on duration.
  • If the current course itself is the longest among those taken, the inner loop can immediately remove it, effectively skipping that course without affecting earlier selections.
  • An empty input list results in an empty ordered list, bypassing all loops and returning zero, which correctly represents that no courses can be taken.
  • The while-condition taken and now > lastday guarantees that the removal step only runs when there is at least one course in the heap and the schedule is actually infeasible, avoiding unnecessary heap operations.

Performance Optimizations

The algorithm incorporates several practical optimizations:

  • Sorting is performed once, establishing a deterministic processing order that eliminates the need for repeated comparisons during iteration.
  • The use of a heap provides logarithmic-time insertion and removal of the longest duration, which is far more efficient than scanning the entire set of taken courses on each deadline violation.
  • By storing negative durations, the code leverages the built-in heapq module without requiring a custom max-heap implementation, reducing overhead.
  • The early removal of impossible courses shrinks the input size for the main loop, decreasing the number of heap pushes and pops.
  • The inner removal loop runs only when the schedule becomes infeasible, and each iteration strictly reduces the total time, ensuring that the loop terminates quickly even in worst-case scenarios.

Overall, the combination of a single sort, a max-heap for dynamic adjustments, and early pruning of hopeless courses yields an implementation that efficiently computes the maximum number of courses that can be completed before their deadlines.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big box of school subjects you want to learn. Each subject has two rules. The first rule is how long it takes to finish learning it, and the second rule is a deadline for when you must be done.

First, the code organizes all the subjects by their deadlines, putting the ones that finish earliest at the front of the line. Before starting, it looks at the list and throws away any subject that is impossible to finish because its deadline comes before the time it would take to even complete the work.

Then, the code starts collecting the subjects onto a tray. It keeps track of the current time by adding up the duration of every subject on the tray. If the total time spent exceeds the deadline for a subject, the code performs a clever trick. It looks through all the subjects currently on the tray, finds the one that took the longest time to learn, and takes it off. By removing the longest subject, more time becomes available, which might make it possible to fit other subjects into the schedule. This way, the goal is to keep as many subjects as possible on the tray while always respecting the deadline for each one.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.07 | σ = 1.44

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
yuanliu666 Kotlin
zfang399 C++
36 links | 23 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

10 solutions   November 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality