LeetCode #1235 Hard

Maximum Profit in Job Scheduling

Maximum Profit in Job Scheduling is LeetCode 1235 (Hard). Job i runs from startTime[i] to endTime[i] and pays profit[i]. Pick jobs that do not overlap and return the largest total profit.

  • A job may start at the exact moment another one ends.
  • There can be 50,000 jobs, so trying every subset (2ⁿ of them) is out. Times go up to 10⁹, so they cannot be used as array indexes either.

The target is O(n log n): one sort plus one binary search per job.

Constraints
  • 1 <= startTime.length == endTime.length == profit.length <= 5 * 10⁴
  • 1 <= startTime[i] < endTime[i] <= 10⁹
  • 1 <= profit[i] <= 10⁴
dpbinary-searchsortingintervals
Open on LeetCode ↗
02

Intuition

This is the classic weighted job scheduling problem. Sort the jobs by end time and let dp[k] be the best profit you can earn using only the first k jobs. Each job then gives a two-way choice:

  • Skip it: the best stays what the earlier jobs already earned.
  • Take it: add its profit to the best plan built only from jobs that finish by its start time.

Because the list is sorted by end time, the jobs that finish by a given start time always form a prefix of the list. A binary search on the end times finds where that prefix stops, so each choice costs O(log n).

How to spot this pattern

Intervals with weights, where you keep a set that never overlaps and maximise the total, is weighted interval scheduling: sort by end, then take or skip with a binary search. If every job had the same profit, the greedy earliest-end rule would be enough.

03

Approach

Try it first

Before reading on, list the jobs by end time for start = [1, 2, 3, 3], end = [3, 4, 5, 6], profit = [50, 10, 40, 70]. For each job, which earlier jobs could run before it? Aim for O(n log n).

1

Sort the jobs by end time

Zip the three lists into (end, start, profit) triples and sort them. After sorting, every job that can run before job k sits somewhere to its left in the list.

2

Keep the end times in their own list

Copy the sorted end times into ends. This list is sorted, so it can be binary searched, and dp gets n + 1 slots with dp[0] = 0 for the plan that uses no jobs.

3

Find how many earlier jobs fit

For job k with start s, prev = bisect_right(ends, s, 0, k) counts the earlier jobs that end at or before s. Those prev jobs are exactly the ones that can sit before job k in a plan.

4

Take the job or skip it

Set dp[k + 1] = max(dp[k], profit + dp[prev]). The first value skips the job and keeps the best plan of the first k jobs; the second takes it on top of the best plan that finishes in time.

5

Why the prefix is all you need

Every job among the first prev ends by s, so any of them can come before job k. Every other earlier job ends after s but no later than job k, so its final stretch lies inside job k's time and they overlap. So dp[prev] is the best plan that fits.

6

Return the last value

dp[n] is the best plan that may use any of the n jobs, so it is the answer.

04

Code in Python, C++ and Java

▶1from bisect import bisect_right
▶2 
▶3class Solution:
▶4 def jobScheduling(self, startTime, endTime, profit):
▶5 jobs = sorted(zip(endTime, startTime, profit))
▶6 ends = [e for e, _, _ in jobs]
▶7 dp = [0] * (len(jobs) + 1)
▶8 for k, (e, s, p) in enumerate(jobs):
▶9 prev = bisect_right(ends, s, 0, k)
▶10 dp[k + 1] = max(dp[k], p + dp[prev])
▶11 return dp[-1]
123456best50104070takeskipjobs sorted by end time, top to bottom
jobs4sorted by end time
dp[0]0no jobs, no profit
Each bar is a job on the timeline, with its profit written inside. Sorting by end time means every job that can run before a given job lies above it. The BEST column will hold the best total using the jobs down to that row.
123456best50104070takeskipfirst job: nothing above it
start1job 1–3
prev0earlier jobs ending by 1
The first job in end order has nothing before it, so taking it can only add to 0.
123456best5050104070take50+0=50profitno jobsskip0best so fartake it: 50 beats 0
take5050 + best of 0
skip0best of 0
dp[1]50
Taking this job earns 50 on top of 0, the best plan among the jobs that fit before it: 50. That beats 0, the best without it, so the job is taken.
123456best5050104070takeskipno earlier job ends by 2
start2job 2–4
prev0earlier jobs ending by 2
The dashed line marks this job's start, 2. No earlier bar ends by then. The red bar runs past 2, so it overlaps this job.
123456best505010504070take10+0=10profitno jobsskip50best so farskip it: 50 beats 10
take1010 + best of 0
skip50best of 1
dp[2]50
Taking this job gives only 10, while the plan without it already earns 50. Skipping keeps the better plan.
123456best505010504070takeskip1 earlier job ends by 3
start3job 3–5
prev1earlier jobs ending by 3
The dashed line marks this job's start, 3. The green bar above ends at or before it, so it can run first. The red bar runs past 3, so it overlaps this job.
123456best50501050409070take40+50=90profitbest of 1skip50best so fartake it: 90 beats 50
take9040 + best of 1
skip50best of 2
dp[3]90
Taking this job earns 40 on top of 50, the best plan among the jobs that fit before it: 90. That beats 50, the best without it, so the job is taken.
123456best50501050409070takeskip1 earlier job ends by 3
start3job 3–6
prev1earlier jobs ending by 3
The dashed line marks this job's start, 3. The green bar above ends at or before it, so it can run first. The red bars run past 3, so they overlap this job.
123456best50501050409070120take70+50=120profitbest of 1skip90best so fartake it: 120 beats 90
take12070 + best of 1
skip90best of 3
dp[4]120
Taking this job earns 70 on top of 50, the best plan among the jobs that fit before it: 120. That beats 90, the best without it, so the job is taken.
123456best50501050409070120takeskipanswer120answer: 120
return120
The last BEST value, 120, may use any job. Walking back through the take decisions recovers the plan: the green bars never overlap and their profits add up to 120.
05

Common pitfalls

Treating jobs that touch as overlapping

✗ Wrong
prev = bisect_left(ends, s, 0, k)
✓ Right
prev = bisect_right(ends, s, 0, k)

bisect_left stops before any job that ends exactly at s, so back-to-back jobs are never combined. With start = [1, 3], end = [3, 5], profit = [20, 20] it returns 20 instead of 40.

Picking jobs greedily by end time

✗ Wrong
for e, s, p in jobs:
    if s >= last_end:
        total += p
        last_end = e
✓ Right
prev = bisect_right(ends, s, 0, k)
dp[k + 1] = max(dp[k], p + dp[prev])

Earliest end first is right when every job is worth the same, but profits break it. With start = [1, 2], end = [3, 5], profit = [1, 100] the greedy takes the first job and is then blocked, returning 1 instead of 100.

Always taking the current job

✗ Wrong
dp[k + 1] = p + dp[prev]
✓ Right
dp[k + 1] = max(dp[k], p + dp[prev])

Without the skip option, dp[k + 1] can be smaller than dp[k]. With start = [1, 2], end = [3, 4], profit = [50, 10] the last value is 10, although taking only the first job earns 50.

06

Edge cases

Every job overlaps every other, as in start = [1, 1, 1], end = [2, 3, 4], profit = [5, 6, 4]

Each binary search returns 0, so taking a job always means taking it alone. dp keeps the largest single profit, 6.

07

Complexity

Time
O(n log n)
Space
O(n)
Sorting costs O(n log n), and each of the n jobs does one O(log n) binary search. The sorted jobs, ends and dp each hold n entries.
08

Three job problems that look alike

What each job carries decides the method.

ProblemEach job hasGoalMethod
Maximum Profit in Job Schedulingfixed start, end and profitlargest total profitsort by end, take-or-skip DP, binary search
N meetings in one roomfixed start and endmost jobsgreedy: earliest end first
Job sequencing with deadlinesdeadline, one time unit, profitlargest profit by the deadlinesgreedy: highest profit into the latest free slot
09

Maximum Profit in Job Scheduling FAQ

Can I sort by start time instead?

Yes, and many solutions do. Sort by start, fill dp from the right so dp[i] is the best profit from job i onward, and binary search the start times for the first job that starts at or after job i ends. The cost is the same; end-time order just reads left to right along the timeline.

Is there a version with a heap instead of binary search?

Sort by start time and keep a min-heap of (end, total) for plans still running. Before each job, pop every plan that ends by its start and keep the best popped total; then push (end, best + profit). The answer is the best total after draining the heap. It is also O(n log n).

How do I list which jobs were chosen?

Store prev for every job. Walk back from k = n: if dp[k] equals dp[k - 1], job k - 1 was skipped, so step to k - 1; otherwise it was taken, so record it and jump to its prev.