Editor

Tasks with a Cooldown

#163 · Greedy · Advanced · 150 XP · about 30 min

A machine has a list of tasks to run, each named by a capital letter, and each takes one unit of time. After running a task, the machine must let at least n units pass before it runs a task with the same letter again; in the meantime it can run other tasks or stand idle. The tasks can be run in any order.

Write least_time(tasks, n) that returns the smallest number of time units needed to finish every task, idle units included.

Examples

least_time(["X", "X", "X", "Y"], 2)                           # returns 7
least_time(["A", "B", "C", "A", "B"], 1)                      # returns 5
least_time(["P", "P", "P", "P", "Q", "Q", "Q", "Q", "R"], 3)  # returns 14

In the first example one best order is X, Y, idle, X, idle, idle, X: 7 units.

Constraints

  • 1 <= len(tasks) <= 10000
  • 0 <= n <= 100

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.