KatInterview

Maximize Profit from Weighted Deadline-Constrained Tasks

Greedy & IntervalsAuto-graded · 17 test cases
HardAuto-gradedGreedy & Intervalsgreedyschedulingunion-find

Last updated

Tests the classic weighted job scheduling with deadlines: greedily select a maximum-profit feasible subset of unit-length tasks, each with a deadline and profit, using a disjoint-set (union-find) structure for efficiency.

Task Scheduler with Deadlines

You are managing a single-machine task queue. You are given n tasks, where each task has:

  • a profit (positive integer) earned if the task is completed, and
  • a deadline (positive integer): the task must be started and finished within time slots 1 through deadline, inclusive.

Each task takes exactly one time slot to complete. The machine can run at most one task per time slot. You may choose any subset of tasks and assign each chosen task to a distinct time slot that does not exceed its deadline.

Your goal is to select a subset of tasks and assign them to time slots so that the total profit is maximized.

Return the maximum total profit achievable.


Details

  • Time slots are numbered 1, 2, 3, ….
  • A task with deadline d can be placed in any of the slots 1, 2, …, d.
  • Each slot can hold at most one task.
  • You do not have to schedule all tasks; unscheduled tasks contribute 0 profit.
  • If no tasks can be scheduled (e.g., the list is empty), return 0.

Constraints

  • 0 ≤ n ≤ 2000 (number of tasks)
  • 1 ≤ profit ≤ 10^6 for each task
  • 1 ≤ deadline ≤ n for each task (deadlines are capped at n since scheduling beyond n slots is never necessary)
  • tasks is a list of [profit, deadline] pairs (each a two-element list of ints)

Examples

Example 1

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

Output: 142

Example 2

Input: max_profit_scheduling([[50, 1], [10, 1], [20, 1]])

Output: 50

Example 3

Input: max_profit_scheduling([])

Output: 0

Hints

Hint 1

Sort tasks in decreasing order of profit; greedily try to schedule each task in the latest available slot at or before its deadline.

Hint 2

To efficiently find the latest free slot ≤ d, use a union-find (disjoint set union) structure where each slot points to the latest free slot at or before it.

Hint 3

When a slot s is occupied, union it with slot s−1 so that future queries for slot s immediately redirect to the next free slot below s.