Job Sequencing Problem

medium

You are given a list of jobs, where each job is a pair [deadline, profit]. Every job takes exactly one unit of time, only one job can run at a time, and a job earns its profit only if it finishes on or before its deadline (time runs in unit slots 1, 2, 3, ...).

Return a two-element array [count, total_profit]: the maximum number of jobs you can complete on time and the maximum total profit achievable.

Hints

Every job takes the same time, so which jobs would you rather keep?
Sort by profit descending and try to schedule the most profitable jobs first.
Place each job in the latest free slot on or before its deadline, freeing early slots for tight deadlines.

Common doubts

A job with a far deadline is flexible; using its latest slot preserves the scarce early slots for jobs that can only run early. It never reduces how many jobs fit.
Since all jobs take equal time, the goal is to keep the highest-profit set that fits. Deadlines only constrain where a kept job goes, not which to prefer.
When deadlines (and thus the slot range) are large: it replaces an O(maxDeadline) scan per job with a near-constant lookup.

Interview follow-ups

Then it's no longer this clean greedy — unequal durations turn it into a weighted scheduling / DP problem.
Store the job id in each slot as you claim it; the filled slots, read left to right, give the schedule.

Fun facts

  • The Union-Find-over-slots trick here is the same 'point to the next available' idea used for offline interval allocation and paint-fill problems.
  • This is a matroid: the schedulable sets of jobs form a transversal matroid, which is why the greedy-by-profit is provably optimal.

Asked at

AmazonMicrosoftFlipkart
Frequently Sometimes Occasionally
Example 1
Input: jobs = [[2,100],[1,19],[2,27],[1,25],[1,15]]
Output: [2, 127]
Schedule [2,100] in slot 2 and [2,27] in slot 1 — 2 jobs, total profit 127.
Example 2
Input: jobs = [[4,20],[1,10],[1,40],[1,30]]
Output: [2, 60]
Take [1,40] in slot 1 and [4,20] in slot 4 — 2 jobs, total profit 60.
Constraints

- 1 <= jobs.length <= 10^5 - 1 <= deadline <= jobs.length - 1 <= profit <= 500

Solve this problem →