KatInterview

Assign Tasks to Time Slots with Minimum Idle Penalty

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

Last updated

Tests the exchange-argument greedy technique by scheduling deadline-bearing tasks into time slots to minimize total weighted idle (missed-deadline) penalty.

Assign Tasks to Time Slots with Minimum Idle Penalty

You are managing a single-worker pipeline. The worker processes one task per time slot, using slots numbered 1, 2, 3, ….

You are given n tasks. Each task i is described by two values:

  • deadlines[i] — the latest slot by which task i must finish (1-indexed, inclusive). If the task is not scheduled in any slot ≤ deadlines[i], it incurs a penalty.
  • penalties[i] — the non-negative integer penalty incurred if task i misses its deadline.

You may schedule at most one task per slot. You do not have to schedule every task; any task left unscheduled also incurs its full penalty.

Your goal is to select a subset of tasks to schedule (one per slot, each in a slot ≤ its deadline) so that the total penalty of all unscheduled/missed tasks is minimized.

Return the minimum total penalty.


How the greedy works (hint-free version)

Think carefully about which tasks are worth keeping "on time" and which you are willing to sacrifice — and in what order you should make that decision.


Constraints

  • 1 ≤ n ≤ 2000 where n = len(deadlines) = len(penalties)
  • 1 ≤ deadlines[i] ≤ n
  • 0 ≤ penalties[i] ≤ 10^6
  • Both lists have the same length.
  • If deadlines and penalties are empty, return 0.

Examples

Example 1

Input: min_idle_penalty([2, 1, 2, 1, 3], [20, 15, 10, 5, 1])

Output: 15

Example 2

Input: min_idle_penalty([1, 1, 1], [10, 30, 20])

Output: 30

Example 3

Input: min_idle_penalty([], [])

Output: 0

Hints

Hint 1

Sort tasks by deadline first. Among tasks with the same deadline, think about which one you'd rather drop if you can only keep a limited number.

Hint 2

Use an exchange argument: suppose you've decided on a set of on-time tasks. If a slot is over-committed (more tasks than slots ≤ their deadline), dropping the task with the smallest penalty in that group costs the least.

Hint 3

Maintain a min-heap of penalties for tasks you've tentatively scheduled. When adding a new task would exceed the available slots up to its deadline, evict the task with the smallest penalty from the heap (it joins the 'missed' pile).