You are given a list of online courses. Course i is described by courses[i] = [duration, lastDay]: it takes duration days in a row, and it must be finished on or before day lastDay.
You start on day 1 and can only take one course at a time. Return the largest number of courses you can complete.
Example 1
Input: courses = [[2, 7], [5, 5], [3, 9], [4, 6]] Output: 3 Why: take 4/6, 2/7 and 3/9; they end on days 4, 6 and 9
2 more examples and the constraints
Example 2
Input: courses = [[4, 3]] Output: 0 Why: the course is longer than the time it allows
Example 3
Input: courses = [[1, 2], [2, 3], [3, 10]] Output: 3 Why: in order they end on days 1, 3 and 6
Constraints
- 1 ≤ number of courses ≤ 10,000
- 1 ≤ duration, lastDay ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Greedy, scan for the longestO(n²)
- Greedy with a max-heapO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 courses | Verdict |
|---|---|---|---|
| Greedy, scan for the longest | O(n²) | Right idea; slow drops | |
| Greedy with a max-heap | O(n log n) | Best; O(log n) drops |
n = how many courses there are.
Edge cases to test
- A course longer than its window. [[4, 3]] can never be taken, so the answer is 0.
- Everything fits. [[1, 2], [2, 3], [3, 10]] takes all three.
- Same last day. [[3, 5], [2, 5], [1, 5]]: only 2 fit; the 3-day one is dropped.
- A long early course. In Example 1, the 5/5 course is taken first, then swapped out for the 4-day one.
- Input order. The input is not sorted; sorting by last day is part of the solution.
Common mistakes
- Sorting by duration instead of by last day, which takes short courses that close too late to matter first.
- Skipping a course that does not fit instead of swapping it with a longer one already taken.
- Dropping the most recent course rather than the longest, which keeps more days used than needed.
How to talk through it
- 1Clarify. Must a course run on consecutive days? Is the last day inclusive? Can courses share a last day?
- 2Give the first greedy. Sort by last day, take each course, and when late, scan for the longest and drop it: O(n²).
- 3Argue why it works. Deadline order is always a valid schedule, and dropping the longest keeps the count while freeing the most days.
- 4Code the heap. Swap the scan for a max-heap of durations: push each, pop the top when late.
- 5Test out loud. Run a single impossible course, a set that all fits, and Example 1 with its swap before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?