~/problems / Greedy

Order tasks to maximise deadline reward

easy ~15 min

Write max_reward(tasks: list[tuple[int, int]]) -> int.

Each task is (duration, deadline). You do every task exactly once, one after another, starting at time 0 with no gaps. Finishing a task at time f earns deadline - f, which is negative if you finish late. Return the largest possible total reward over all orders.

Example: [(6, 10), (8, 15), (5, 12)] gives 2. The order 5, 6, 8 finishes at times 5, 11, 19, earning (12 − 5) + (10 − 11) + (15 − 19) = 2. An empty task list gives 0.

Constraints: up to 2 * 10^5 tasks, 1 <= duration, deadline <= 10^6.

Trying orders is hopeless at this size; aim for O(n log n).

Show hint

write the total as sum(deadlines) - sum(finish times). Which part depends on the order, and what order makes it smallest?

Topic: Greedy with sorting. Sort, then take the locally best choice; prove it with an exchange argument.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc