KatInterview

Maximize Completed Jobs with Deadlines

Greedy & IntervalsAuto-graded · 17 test cases
MediumAuto-gradedGreedy & Intervalsgreedyschedulingsorting

Last updated

Tests greedy scheduling with deadlines: select and order unit-length jobs to maximize total profit, applying an exchange argument to prove optimality.

Maximize Completed Jobs with Deadlines

You are managing a single-machine workshop. A list of jobs arrives, each requiring exactly one time slot to complete. Time slots are numbered 1, 2, 3, ….

Each job has:

  • A deadline d (positive integer): the job must finish on or before slot d.
  • A profit p (non-negative integer): earned only if the job is completed by its deadline.

You may schedule at most one job per time slot, and you are free to leave slots empty. A job completed in slot t satisfies its deadline if and only if t <= d.

Your goal is to choose a subset of jobs and assign each to a distinct time slot (respecting deadlines) so that the total profit is maximised. Return that maximum total profit.

If multiple jobs share the same deadline and profit, they are interchangeable — the answer is the same regardless of which one you pick.

Constraints

  • 1 <= len(jobs) <= 2000
  • Each element of jobs is a two-element list [d, p].
  • 1 <= d <= 2000
  • 0 <= p <= 10_000
  • There is always at least one job (the list is non-empty).

Examples

Example 1

Input: max_profit_schedule([[4, 20], [1, 10], [1, 40], [1, 30]])

Output: 60

Example 2

Input: max_profit_schedule([[2, 100], [2, 19], [1, 27], [3, 25], [3, 15]])

Output: 152

Example 3

Input: max_profit_schedule([[1, 5], [1, 5], [1, 5]])

Output: 5

Hints

Hint 1

Sort jobs by profit in descending order so you always try to include the most valuable job first.

Hint 2

For each job (in profit order), greedily assign it to the latest available slot that is still <= its deadline. This keeps earlier slots free for jobs with tighter deadlines.

Hint 3

Use a simple boolean array of size max_deadline+1 to track which slots are occupied, and scan backwards from the job's deadline to find a free slot in O(d) time per job.