Maximum Profit in Job Scheduling

50 min · jobScheduling()

A packed calendar isn't necessarily a profitable one. Sometimes skipping a long job makes room for several better jobs.

You're given three equal-length arrays describing n jobs. Job i starts at startTime[i], ends at endTime[i], and earns profit[i]. Choose non-overlapping jobs whose total profit is as large as possible, then return that total.

Each job occupies the half-open interval [start, end): it includes its start time but not its end time. That means a job may start at the exact moment another one ends.

A few ground rules:

  • You may take each job at most once.
  • Jobs may arrive in any input order.
  • You may skip any job; profits are positive, so the best total is always positive.

Constraints

  • 1 <= n <= 50_000
  • startTime.length == endTime.length == profit.length == n
  • 1 <= startTime[i] < endTime[i] <= 1_000_000_000
  • 1 <= profit[i] <= 10_000
  • The total of all profits is at most 500_000_000, so every answer fits signed 32-bit.

Hints

Choose a useful order

Sort jobs by end time. Then every job that could come before the current one appears somewhere to its left.

Take it or leave it

Use dynamic programming (DP), which stores answers to smaller prefix problems. For the next job, compare skipping it with taking it after the best compatible prefix.

Find the prefix faster

The sorted end times never decrease. Binary-search for the rightmost earlier job whose end time is at most the current start time; equality must count as compatible.

Follow-up

Could you return the original indices of one optimal set of jobs as well as its profit?

Visible cases

Examples

Example 1

ready
Input
startTime = [
  1,
  2,
  3,
  3
]
endTime = [
  3,
  4,
  5,
  6
]
profit = [
  50,
  10,
  40,
  70
]
Expected
120
Why
take [1,3) for 50 and [3,6) for 70

Example 2

ready
Input
startTime = [
  1,
  2,
  3,
  4,
  6
]
endTime = [
  3,
  5,
  10,
  6,
  9
]
profit = [
  20,
  20,
  100,
  70,
  60
]
Expected
150
Why
the jobs [1,3), [4,6), and [6,9) earn 20 + 70 + 60

Example 3

ready
Input
startTime = [
  1,
  1,
  1
]
endTime = [
  2,
  3,
  4
]
profit = [
  5,
  6,
  4
]
Expected
6
Why
all three jobs overlap, so choose the most profitable one

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite