Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Intervals

Most profit from jobs that do not overlap

Hard · Target 30 minutes · Intervals · Type asked atCitadelTwo SigmaGoogle

Each job is a triple [start, end, profit] with start < end and profit > 0. You can do at most one job at a time, and a job that ends at time t can be followed by one that starts at t. Return the largest total profit you can earn.

Examples

InputOutputWhy
jobs = [[1, 3, 50], [2, 4, 10], [3, 5, 40], [3, 6, 70]]120Take [1, 3, 50] and then [3, 6, 70].
jobs = [[1, 3, 20], [2, 5, 20], [3, 10, 100], [4, 6, 70], [6, 9, 60]]150[1, 3, 20] then [3, 10, 100]: 120. Better: [1, 3, 20], [4, 6, 70], [6, 9, 60] is 150.
jobs = [[1, 2, 5], [1, 3, 6], [1, 4, 4]]6All three overlap; take the most valuable.

Constraints

  • 1 ≤ n ≤ 5·10⁴
  • 0 ≤ start < end ≤ 10⁹
  • 1 ≤ profit ≤ 10⁴

Hints

Hint 1

The previous problem's rule, keep the job that ends earliest, ignores profit. Find an example where it loses money.

Hint 2

Sort the jobs by end time. For the i-th job there are two choices: skip it, or take it together with the best schedule of jobs that end by its start.

Hint 3

best[i] = max(best[i − 1], profit[i] + best[k]), where k counts the jobs that end at or before job i starts. Find k by binary search on the sorted end times.

Where people lose marks

  • Greedy by earliest end or by highest profit: both have counterexamples, including the second example above.
  • Searching for end times strictly less than the start: a job ending at t is compatible with one starting at t.
  • Indexing best[] by job rather than by prefix length, which makes "no compatible job" awkward; best[0] = 0 handles it.
  • Recursing over every subset: exponential, and the subproblems repeat.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.