iq.lab
Python starts when a code cell comes near or you run one
mediumHeapsGreedy choice target 25 min

Jobs with a cooldown

A machine has a list of jobs to run, tasks. Each job is a capital letter that names its kind, such as "A". Time passes in ticks: in each tick the machine runs one job or sits idle.

The machine must cool down between jobs of the same kind: between two jobs of the same kind there must be at least n other ticks, filled with other jobs or left idle. Jobs of different kinds can run back to back, and you may run the jobs in any order.

Return the smallest number of ticks that runs every job, as an integer. The count stops at the last job: no idle ticks are added after it.

Example 1
Inputtasks = ["A", "A", "A", "B", "B"], n = 2Output7

One best order is A, B, idle, A, B, idle, A. Each pair of A's has two ticks between them.

Example 2
Inputtasks = ["A", "A", "B", "B"], n = 2Output5

A, B, idle, A, B. A and B tie for the most jobs, so the order ends with one of each.

Example 3
Inputtasks = ["A", "A", "B", "B", "C", "C"], n = 2Output6

A, B, C, A, B, C. Three kinds fill every gap, so no tick is idle.

Constraints
  • 1 ≤ len(tasks) ≤ 105

  • Each job is a capital letter from A to Z, so there are at most 26 kinds.

  • 0 ≤ n ≤ 100

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.