progress

~/problems / Greedy

Order tasks to maximise deadline reward

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

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

Each task is (duration, deadline). You do every task once, back to back from time 0. Finishing a task at time f earns deadline - f, negative if late. Return the largest 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.

Up to 2 * 10^5 tasks, 1 <= duration, deadline <= 10^6.

⭐ Bonus: a speed test with 200,000 tasks earns a star in O(n log n). Trying orders is hopeless.

Show hint

write the total as sum(deadlines) - sum(finish times). Which part depends on the order?

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