Course Schedule III
Fit as many courses as possible into your days when each course has its own last day to finish.
There are n online courses, given as an array coursescourses[i] = [duration, lastDay]durationlastDay
Example 1
Output: 3
Example 2
Output: 1
Example 3
Output: 2
Explanation: taking the 5-day course first leaves no room for either of the others. Taking the 4-day and then the 2-day course finishes on day 6.
The Idea
Think of a list of short online courses, each with a last day by which it must be done. Some courses clash, so you cannot take them all, and the question is how many you can fit. Each course is a pair: [5, 5]
Example 3 has three courses: [5, 5][4, 6][2, 6]
So the first course you pick can block later ones. Which courses should you keep, and in what order?
Order is the easier half. Take a plan that finishes on time, where a course with a later last day runs right before one with an earlier last day. Swap the two. The earlier-deadline course now ends sooner. The other one now ends where the earlier-deadline course used to end, which was on time for the earlier last day, so it is on time for its own later one too. So any set of courses that can be finished at all can be finished in order of last day. From now on, go through the courses sorted by lastDay
Now the choice. Add each new course to the plan. If the plan then ends after the new course's last day, one course has to leave. Which one? Look at the picture below, which follows Example 3 in last-day order.
The row labelled "take [5, 5]" ends on day 5, right at its last day. In the row labelled "add [4, 6]", the plan runs to day 9, past lastDay 6. Dropping either course leaves one course, so the count is the same whichever goes. What differs is how early the plan ends. Dropping the longest, the 5-day course, gives the row labelled "drop the longest: 5-day", which ends on day 4. In the last row the 2-day course fits, and the plan ends on day 6 with two courses.
That is the key insight: take every course in last-day order, and whenever the plan runs late, drop the longest course in it. The count stays where it was, and the plan ends as early as it can, which leaves the most room for the courses still to come.
Solution Approach
Turning that idea into code means settling three things: why not simply try every set of courses, how to find the longest course in the plan quickly, and why one drop is enough when the plan runs late.
Trying every set of courses
What is the simple way? Try every set of courses, check each one in last-day order, and keep the biggest set that fits. With n courses there are 2n sets, so 30 courses already give over a billion. Going through the sorted courses once and dropping when late replaces all of that with one pass.
Finding the longest course quickly
Each time the plan runs late, we need the longest course in it. Scanning the whole plan every time costs up to n steps per course. A heap does better: it keeps its items so that the biggest (or the smallest) is always at the front, and adding or removing an item takes about log n steps.
In Java, a heap comes ready-made as PriorityQueueCollections.reverseOrder()poll()
Dropping one course after a late add
Is one drop always enough? Before the new course was added, the plan ended on or before the last day of the course looked at just before, and in sorted order that day is no later than the new course's last day. The longest course in the plan is at least as long as the new one, so removing it brings the plan back to that earlier end day or sooner.
Why not just skip the new course when it does not fit? That keeps whatever was chosen first. In Example 3 it keeps the 5-day course, and a version written that way prints 1 instead of 2. Dropping the longest course can swap out an early choice that later turns out to be expensive.
Java Solution
The method scheduleCourse
- First, copy the array with
intocourses.clone() , and sort the copy by last day withsorted and a comparator onArrays.sort . Sorting a copy leaves the caller's array in its original order.a[1] - Create the max-heap
, ataken built withPriorityQueue , for the durations of the courses in the plan. Next to it,Collections.reverseOrder() counts the days the plan uses, starting at 0.time - Loop over the sorted courses. For each one, read
andduration , addlastDay toduration , and add it totaken .time - If
is now greater thantime , remove the longest duration withlastDay and subtract it fromtaken.poll() .time - After the loop, every duration left in
is a course in the plan, so returntaken .taken.size()
The main
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;
public class CourseScheduleIII {
public static int scheduleCourse(int[][] courses) {
int[][] sorted = courses.clone();
Arrays.sort(sorted, (a, b) -> Integer.compare(a[1], b[1])); // earliest deadline first
// Durations of the courses taken so far, longest on top (a max-heap).
PriorityQueue<Integer> taken = new PriorityQueue<>(Collections.reverseOrder());
int time = 0; // days used by the taken courses
for (int[] course : sorted) {
int duration = course[0];
int lastDay = course[1];
taken.add(duration);
time += duration;
if (time > lastDay) {
time -= taken.poll(); // too late: drop the longest course
}
}
return taken.size();
}
public static void main(String[] args) {
System.out.println(scheduleCourse(
new int[][] {{100, 200}, {200, 1300}, {1000, 1250}, {2000, 3200}}));
System.out.println(scheduleCourse(new int[][] {{1, 2}}));
System.out.println(scheduleCourse(new int[][] {{5, 5}, {4, 6}, {2, 6}}));
System.out.println(scheduleCourse(new int[][] {{3, 2}}));
System.out.println(scheduleCourse(
new int[][] {{7, 17}, {3, 12}, {10, 20}, {9, 10}, {5, 20}, {10, 19}, {4, 18}}));
}
}
Running it prints:
3
1
2
0
4
Look at the first line, 3, from Example 1. In last-day order the courses are [100, 200][1000, 1250][200, 1300][2000, 3200]
The fourth line, 0, comes from [[3, 2]]
The last line, 4, comes from the seven courses. The plan runs late when [7, 17]
Complexity
The work is the sort, plus at most one heap add and one heap removal for each course.
- Time: O(n log n), because sorting the n courses by last day takes n log n steps, and each course then costs one
and at most oneadd on a heap of at most n durations, about log n steps each.poll - Space: O(n), because the sorted copy holds n references to the course pairs and the heap holds every duration when all the courses fit.
The same "take it, and drop the worst one when over the limit" idea solves