Maximum Profit in Job Scheduling

Choose jobs that do not overlap in time so that their total profit is as large as possible.

You are given n jobs as three arrays of the same length. Job i runs from startTime[i] to endTime[i] and earns profit[i]. Choose jobs that do not overlap in time, and return the largest total profit they can earn. A job that ends at time X does not overlap a job that starts at X.

Example 1
Input: startTime = [1, 2, 3, 3], endTime = [3, 4, 5, 6], profit = [50, 10, 40, 70]
Output: 120
Explanation: the jobs 1-3 and 3-6 earn 50 + 70.
Example 2
Input: startTime = [1, 2, 3, 4, 6], endTime = [3, 5, 10, 6, 9], profit = [20, 20, 100, 70, 60]
Output: 150
Explanation: the jobs 1-3, 4-6 and 6-9 earn 20 + 70 + 60.
Solution

The Idea

Picture a freelancer who is offered a few jobs. Each job has a start time, an end time and a profit, the money it pays, and she can work on only one job at a time. Which jobs should she accept to earn the most?

Example 1 offers four jobs: 1-3 pays 50, 2-4 pays 10, 3-5 pays 40 and 3-6 pays 70. Job 1-3 ends at 3 and job 3-6 starts at 3, so she can do both and earn 120.

Why not simply grab the best-paying job first? In Example 2, job 3-10 pays 100, more than any other job. But it runs over the jobs 4-6 and 6-9, and together with 1-3 those three earn 20 + 70 + 60 = 150. Taking the job that ends first fails too. In Example 1 that takes 1-3, then 3-5, the next job to end that still fits, and stops at 90.

So no simple rule picks the jobs. Each job needs a real choice: take it or skip it. Trying every combination of choices means 2 multiplied by itself once per job: about a million combinations for just 20 jobs. How can we decide each job without trying them all?

Put the jobs in order of the time they end, go through them one by one, and write down the best profit so far after each job. Look at the picture below.

The four jobs of Example 1 on a time line, sorted by end time, with the best profit so far after each: 50, 50, 90, 120. Job 3-6 starts at 3, and only job 1-3 ends by 3, so taking 3-6 gives 50 + 70 = 120, more than skipping it, 90.

The jobs are drawn on a time line, one row each, from the one that ends first to the one that ends last. The column on the right shows the best profit so far. After 1-3 it is 50. Job 2-4 overlaps 1-3 and pays less, so the best stays 50. Job 3-5 starts as 1-3 ends, so 50 + 40 gives 90.

Now the last row, job 3-6. The dashed line marks its start, 3. Only job 1-3 ends by 3, so taking 3-6 earns its 70 plus the best profit from 1-3 alone, 50, which is 120. Skipping 3-6 keeps the best profit from the three jobs above it, 90. The larger one, 120, is the answer.

So the best profit after each job comes from two numbers already written down: the one just above it (skip), and the one in the row of the last job that ends by its start, plus the job's own profit (take). Building an answer from smaller answers that were already worked out is called dynamic programming.

Solution Approach

Turning that idea into code means settling three things: how to put the jobs in order, what to write down for each job, and how to find the jobs that end in time.

Ordering the jobs by end time

Why order by end time and not by start time? Sorted by end time, the jobs that end by a given start form a block at the front of the order, with no gaps. In the picture, the jobs that end by 3 are just the first row.

The three arrays must not be sorted on their own, or a job's start, end and profit would get separated. Instead, an array of positions 0, 1, 2 and so on is sorted by the end time at each position. Each position still points at all three values of its job.

The best profit table

What exactly do we write down? Let best[i] be the most profit from the first i jobs in end-time order, with best[0] = 0 for no jobs at all. For the next job, let fits be how many jobs end by its start. Then best[i + 1] is the larger of best[i], for skipping the job, and best[fits] plus its profit, for taking it.

Why is best[fits] the right number to add the profit to? The first fits jobs all end by its start, so any choice among them can go with it. Every other job before it in the order ends after the start but no later than the job's own end, so it overlaps the job. Nothing that could go with the job is left out.

Finding the jobs that end in time

How do we get fits? The simple way is to count backwards over the earlier jobs, but that can take n steps for each job, n² steps in all. Since the end times are sorted, a binary search is faster: look at the middle end time, and keep only the half that can still hold the answer. Each look halves the range, so it takes about log₂ n looks.

The search counts end times that are less than or equal to the start, not strictly less. That is what lets a job that ends at 3 go with a job that starts at 3.

Java Solution

The method jobScheduling works in these steps:

  1. First, fill an array order with the positions 0 to n - 1, and sort it by end time with Arrays.sort and Integer.compare(endTime[a], endTime[b]).
  2. Create two arrays: ends, which collects the end times in sorted order, and best, with n + 1 places, where best[0] is 0.
  3. One loop then goes over the jobs in sorted order. For position i, job is order[i], and its end time goes into ends[i].
  4. Inside the loop, the helper countEndingBy runs a binary search over the first i entries of ends. It returns fits, the number of earlier jobs that end by the job's start.
  5. Still inside the loop, set best[i + 1] to the larger of best[i] (skip) and best[fits] + profit[job] (take).
  6. When the loop is done, return best[n], the best profit over all the jobs.

The main method runs both examples, three jobs that all start at 1, two touching jobs given with the later one first, and a single job.

Java
import java.util.Arrays;

public class MaximumProfitInJobScheduling {

    public static int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
        int n = startTime.length;
        Integer[] order = new Integer[n];
        for (int i = 0; i < n; i++) {
            order[i] = i;
        }
        Arrays.sort(order, (a, b) -> Integer.compare(endTime[a], endTime[b]));

        int[] ends = new int[n];
        int[] best = new int[n + 1];   // best[i]: most profit from the first i jobs by end time
        for (int i = 0; i < n; i++) {
            int job = order[i];
            ends[i] = endTime[job];
            int fits = countEndingBy(ends, i, startTime[job]);  // jobs 0..fits-1 end in time
            best[i + 1] = Math.max(best[i], best[fits] + profit[job]);  // skip or take
        }
        return best[n];
    }

    // How many of ends[0..count-1] are <= time. ends is sorted, so binary search.
    private static int countEndingBy(int[] ends, int count, int time) {
        int lo = 0;
        int hi = count;
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (ends[mid] <= time) {
                lo = mid + 1;        // ends[mid] is in time: the answer is to the right
            } else {
                hi = mid;            // ends[mid] is too late: the answer is mid or left
            }
        }
        return lo;
    }

    public static void main(String[] args) {
        System.out.println(jobScheduling(new int[] {1, 2, 3, 3}, new int[] {3, 4, 5, 6},
                new int[] {50, 10, 40, 70}));
        System.out.println(jobScheduling(new int[] {1, 2, 3, 4, 6}, new int[] {3, 5, 10, 6, 9},
                new int[] {20, 20, 100, 70, 60}));
        System.out.println(jobScheduling(new int[] {1, 1, 1}, new int[] {2, 3, 4},
                new int[] {5, 6, 4}));
        System.out.println(jobScheduling(new int[] {4, 1}, new int[] {6, 4},
                new int[] {30, 20}));
        System.out.println(jobScheduling(new int[] {7}, new int[] {9}, new int[] {25}));
    }
}

Running it prints:

Output
120
150
6
50
25

The first two lines are the two examples, 120 and 150. The third line is 6: the jobs 1-2, 1-3 and 1-4 all start at 1, so only one of them can be picked, and the one paying 6 wins.

Look at the fourth line. The input lists job 4-6 before job 1-4, and sorting by end time puts them the right way round. The two jobs touch at 4, so both are taken, for 20 + 30 = 50. The last line shows that a single job simply earns its own profit, 25.

The fourth line also depends on the <= in countEndingBy. With a strict <, touching jobs count as overlapping. That version prints 70, 100, 6, 30 and 25: the first, second and fourth answers all drop, because the jobs that meet end to start can no longer be combined.

Complexity

The work is the sort, plus one binary search for each job.

  • Time: O(n log n), where n is the number of jobs. Sorting the positions takes O(n log n), and the loop runs one binary search of O(log n) steps per job.
  • Space: O(n). order, ends and best each hold about n values, and the binary search keeps only lo, hi and mid.

The same "take it or skip it" choice, built on an earlier answer that does not clash, is the heart of House Robber.