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 courses. Each entry courses[i] = [duration, lastDay] describes a course that takes duration days in a row and must be finished on or before day lastDay. You start on day 1 and can take only one course at a time. Return the largest number of courses you can finish.

Example 1
Input: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]
Output: 3
Example 2
Input: courses = [[1,2]]
Output: 1
Example 3
Input: courses = [[5,5],[4,6],[2,6]]
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.
Solution

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] takes 5 days and must be finished by day 5.

Example 3 has three courses: [5, 5], [4, 6] and [2, 6]. Start with the 5-day course and it ends on day 5. The 4-day course would then end on day 9 and the 2-day course on day 7, both past day 6, so that plan ends with one course. Start with the 4-day course instead, add the 2-day one, and you finish on day 6 with two courses.

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 and keep a plan: the courses chosen so far, taken one after another from day 1.

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.

Example 3 on a day line. Taking [5, 5] ends on day 5. Adding [4, 6] ends on day 9, past lastDay 6. Dropping the longest course, the 5-day one, leaves the 4-day course ending on day 4. Adding [2, 6] ends on day 6, on time.

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 PriorityQueue. By default it keeps the smallest item at the front, which is called a min-heap. Built with the comparator Collections.reverseOrder(), it reverses that order, so the largest duration is at the front: a max-heap. Its poll() method removes and returns that front item. The plan only needs the durations, so the heap holds just those numbers.

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 works in these steps:

  1. First, copy the array with courses.clone() into sorted, and sort the copy by last day with Arrays.sort and a comparator on a[1]. Sorting a copy leaves the caller's array in its original order.
  2. Create the max-heap taken, a PriorityQueue built with Collections.reverseOrder(), for the durations of the courses in the plan. Next to it, time counts the days the plan uses, starting at 0.
  3. Loop over the sorted courses. For each one, read duration and lastDay, add duration to taken, and add it to time.
  4. If time is now greater than lastDay, remove the longest duration with taken.poll() and subtract it from time.
  5. After the loop, every duration left in taken is a course in the plan, so return taken.size().

The main method runs the three examples, a course that takes longer than its own last day, and a set of seven courses where the plan runs late three times.

Java
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:

Output
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] and [2000, 3200]. The first three end on days 100, 1100 and 1300, each on time. The 2000-day course pushes the plan to day 3300, past day 3200, and since it is the longest, it is the one dropped.

The fourth line, 0, comes from [[3, 2]]: a 3-day course cannot end by day 2. It is added, the plan runs late, and the longest course in the heap is that same course, so it leaves at once.

The last line, 4, comes from the seven courses. The plan runs late when [7, 17] arrives, and the 9-day course chosen first is dropped for it. Later, both 10-day courses are dropped right after being added. The plan keeps the 3-, 4-, 5- and 7-day courses and ends on day 19.

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 add and at most one poll on a heap of at most n durations, about log n steps each.
  • 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 Farthest Building You Can Reach.