Maximum Profit in Job Scheduling

HardDynamic programmingLeetCode 1235 ↗World 5-19
0:00 / 0:00

Pick non-overlapping jobs for the most profit: sort by end time, then each job either skips or adds to the best plan a binary search finds.

▼

The problem

LeetCode 1235 (Hard). Job i runs from startTime[i] to endTime[i] and pays profit[i]. Pick jobs with no two overlapping (a job ending at time X is compatible with one starting at X) to make the most total profit.

Example (LeetCode's second, the one animated): startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60] → 150 (1-3, 4-6, 6-9).

TRY IT ON LEETCODE ▶

The solution

from bisect import bisect_right

def jobScheduling(startTime, endTime, profit):
    jobs = sorted(zip(endTime, startTime, profit))
    ends = [e for e, s, p in jobs]
    dp = [0] * (len(jobs) + 1)
    for i, (e, s, p) in enumerate(jobs, 1):
        j = bisect_right(ends, s)
        dp[i] = max(dp[i - 1], p + dp[j])
    return dp[-1]

Transcript

Maximum Profit in Job Scheduling. Each job has a start, an end and a profit. You can't work two jobs that overlap, but one may start right as another ends. Pick jobs to earn the most.

Here are five jobs. One to three pays twenty, two to five pays twenty, three to ten pays a hundred, four to six pays seventy, and six to nine pays sixty. The best: one to three, four to six and six to nine, for one hundred fifty.

The slow way tries every set of jobs. But n jobs make two to the n sets: thirty-two here, and over a trillion for forty.

Greedy fails too. Grab the biggest pay first, and the hundred blocks everything but one to three: one twenty, not one fifty.

Instead, sort the jobs by end time. Let dp of i be the best profit from the first i jobs. Job i is skipped, keeping dp of i minus one, or taken: its profit plus dp of j, where j counts the jobs ending by its start. Keep the larger.

The ends are sorted, so binary search finds j. For the job starting at six, the middle end is six, not past it, so look right. Ten and nine are past it, so look left. Three ends come by six: j is three.

In code, sort by end, list the ends, and fill dp left to right. Bisect right finds j, and each entry keeps the larger choice. Return the last.

Let's walk it. One to three: twenty. Two to five starts before anything ends: taking it gives twenty, no better. Four to six follows one to three: seventy plus twenty, ninety. Six to nine follows four to six: sixty plus ninety, one fifty. Three to ten would give one twenty, so skip it. The answer: one fifty.

Sorting is n log n, plus one binary search per job: order n log n time, and order n space.

Sort by end, search back, take or skip. That's Maximum Profit in Job Scheduling.