Fixed-Order Task Run Time With Cooldown
Problem statement
You are given a string tasks. Each character is a task type, and the tasks must run in exactly the order they appear. You are also given an integer cooldown.
The tasks run on one machine under these rules:
- Each task takes exactly one second, and only one task can run at a time.
- You cannot change the order of the tasks.
- After a task of some type finishes, the next task of the same type can start only after at least
cooldownmore seconds have passed. - While the next task is waiting for its cooldown, the machine stays idle. Tasks of other types and idle seconds both count toward the cooldown.
The first task starts at time 0. Return the total number of seconds needed to finish every task.
Function
taskRunTime(tasks: String, cooldown: int) → intExamples
Example 1
tasks = "ABBCC"cooldown = 3return = 11Track when each task starts and ends:
Aruns from0to1.- The first
Bruns from1to2. - The second
Bmust wait until2 + 3 = 5, so it runs from5to6. - The first
Cruns from6to7. - The second
Cmust wait until7 + 3 = 10, so it runs from10to11.
The last task ends at time 11.
Example 2
tasks = "ABCA"cooldown = 2return = 4A, B, and C run in the first three seconds. The first A ended at time 1, so the second A may start at 1 + 2 = 3. That is exactly when the machine becomes free, so no idle time is needed and the last task ends at time 4.
Example 3
tasks = "AAA"cooldown = 0return = 3With a cooldown of 0, tasks of the same type can run back to back. The three tasks end at time 3.
Constraints
1 <= tasks.length <= 10^5taskscontains only uppercase English letters.0 <= cooldown <= 10^4