Maximum Profit in Job Scheduling

Hard

Topics
ArrayDynamic ProgrammingBinary SearchSorting

You are given n jobs, each described by a row [start, end, profit]. Taking a job earns its profit, but you can only work on one job at a time.

Two jobs may be taken together when they do not overlap. A job ending at time t and a job starting at time t do not overlap — the end is exclusive.

Return the maximum profit obtainable.

The judge names this argument grid, since it feeds every matrix problem through the same reader. It is the jobs table above, one row per job. LeetCode passes three parallel arrays instead.

Example 1

jobs16[1,3][2,4][3,5][3,6]
profit50104070
takenleft out
Each lane is one job’s [start, end) window, and the end is exclusive — a job ending at time t and one starting at t can both be taken. The shaded set does not overlap anywhere and earns 120, which is the most available. Notice that the highest single profit is not always in it.
Lanes are the job windows on a shared time axis; the chips are their profits in input order.
Input:  jobs = [[1,3,50],[2,4,10],[3,5,40],[3,6,70]]
Output: 120
Explanation: Take [1,3) for 50 and [3,6) for 70. The 40 job also starts at 3 but pays less, and taking it would rule out the 70 one.

Example 2

jobs119[1,2][3,5][6,19]
profit5020100
taken
Input:  jobs = [[1,2,50],[3,5,20],[6,19,100]]
Output: 170
Explanation: None of the three overlap, so all can be taken.

Example 3

jobs110[1,10][2,3][4,5]
profit1001010
takenleft out
Input:  jobs = [[1,10,100],[2,3,10],[4,5,10]]
Output: 100
Explanation: The long job blocks both short ones, and still beats their combined 20.

Constraints

  • 1 <= n <= 5 * 10^4
  • 1 <= start < end <= 10^9
  • 1 <= profit <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

Taking the most profitable job first is the natural guess and example 3 breaks it: the 100 job is the best single choice there and happens to be right, but shift the numbers slightly and a long expensive job can block two short ones worth more together.

The decision for one job depends only on what was possible before it starts, which suggests ordering the jobs by their end time. Processed in that order, the answer for "best profit using jobs that finish by time t" only ever grows, so each job can ask one question: what was the best profit available at the moment I start?

That question is a lookup into a table of (end time, best profit so far) that is already sorted by end time, so it is answered by searching for the latest end time that is at most this job’s start. Taking the job gives that profit plus its own; skipping it leaves the running best unchanged, and the larger of the two is recorded.

Approach

  1. Sort the jobs by end time.
  2. Keep a running table of (endTime, bestProfit) pairs, starting with (0, 0). The profits in it are non-decreasing by construction.
  3. For each job in order, find the last entry whose end time is <= this job’s start, and read its profit. That is the best achievable before this job can begin.
  4. The candidate is that profit plus this job’s profit. If it beats the table’s current best, append (thisEnd, candidate); otherwise leave the table alone so it stays non-decreasing.
  5. The last entry’s profit is the answer.

Walkthrough

jobs = [[1,3,50],[2,4,10],[3,5,40],[3,6,70]]
sorted by end: [1,3,50] [2,4,10] [3,5,40] [3,6,70]

job          best before start   candidate   table (end,best)
                                             (0,0)
[1,3,50]     at time 1 -> 0      50          (0,0) (3,50)
[2,4,10]     at time 2 -> 0      10          unchanged, 10 < 50
[3,5,40]     at time 3 -> 50     90          (0,0) (3,50) (5,90)
[3,6,70]     at time 3 -> 50     120         (0,0) (3,50) (5,90) (6,120)

answer 120

The [2,4,10] job is dropped not because 10 is small but
because nothing it could combine with beats what 50 already
achieved by the same time.

Complexity

  • Time — O(n log n): the sort, plus one search per job into a table that is already ordered.
  • Space — O(n): the table holds at most one entry per job.

Common Pitfalls

  • Sorting by start time. The table is built in end-time order, and sorting by start breaks the invariant that everything already in it has finished.
  • Treating a job that starts exactly when another ends as an overlap. The end is exclusive, so those two are compatible, and a strict comparison in the search loses the pairing in example 1.
  • Appending to the table unconditionally. Then the profits are no longer non-decreasing and the search returns a worse value than was actually available.
  • Picking jobs greedily by profit, or by shortest duration. Neither is optimal.
  • mid = (lo + hi) / 2 is the textbook form, and in Java or C++ it is the one that bites: the moment lo + hi passes 2^31 - 1 it wraps negative and the index flies out of range. This problem’s bounds never get close, so the code above is correct as written, but lo + (hi - lo) / 2 is the habit worth keeping — same answer, same cost, no overflow. Python’s integers are arbitrary precision, so it is a non-issue there.

Full Solution — all languages

class Solution:
    def jobScheduling(self, grid):
        import bisect
        jobs = sorted(grid, key=lambda job: job[1])
        ends = [0]
        best = [0]
        for start, end, profit in jobs:
            i = bisect.bisect_right(ends, start) - 1
            candidate = best[i] + profit
            if candidate > best[-1]:
                ends.append(end)
                best.append(candidate)
        return best[-1]
SensAI
Beta
Tap the mic to stop voice mode