DSA Factory
Free Greedy lessonsGreedy · Stage 3 · Exchange arguments · Step 2

Most courses before the deadlines

Take as many courses as possible when each has a length and a last day, by sorting by deadline and dropping the longest course whenever the schedule overruns. About 22 minutes.

Deadlines set the order

Each course takes some days and must be finished by its last day. You take them one after another, with no gaps, and want to take as many as possible.

Sort the courses by last day. If you take a set of courses, doing them in order of last day is always the safest schedule, because the courses with the tightest deadlines go first. Now the only question is which courses to include.

Order by last day, tightest deadline first.
Then decide: which courses stay in the plan.

Swap out the longest

Add courses in deadline order, keeping a running total of days used. If a new course makes the total pass its last day, one course must go.

Drop the longest course taken so far, possibly the new one. Swapping it out keeps the same count but uses the fewest days, so later courses have the most room. A max-heap of lengths gives the longest in logarithmic time.

Over the last day? remove the longest course taken.
The heap size: is the answer at the end.
In code
heapq.heappush(heap, -length)
longest = -heapq.heappop(heap)
Lengths sorted by last day: 50 by day 100, 400 by day 500, 100 by day 600, 700 by day 1100.
50
0
400
1
100
2
700
3
i

Take 50. Time used 50, within day 100.

Move 1 of 4
Quick check

Why drop the longest course when the schedule runs over?

  1. AIt frees the most time and loses only one course
  2. BShort courses are always worth more
  3. CThe latest deadline is always the problem
Show the answer

It frees the most time and loses only one course. Removing any course loses one from the count, so remove the one that frees the most days.

Your problem

Most courses

You are given courses, where courses[i] = [length, lastDay]: the course takes length days and must be finished on or before lastDay. You take courses one at a time, starting on day 1 with no gaps, and each course must be completed before the next starts. Return the largest number of courses you can take.

Example
courses = [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]] → 3

1 ≤ courses.length ≤ 10,000 · 1 ≤ length, lastDay ≤ 10,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve