Program to find minimum time required to complete tasks with k time gap between same type tasks in Python

Suppose we have a list of integers called tasks where each item represents a different task type, we also have a non-negative integer say k. Each task takes one unit of time to complete and the tasks must be completed in correct order, but we must have k units of time between doing two same type tasks. At any time, either we can do a task or wait. We have to find the amount of time it takes to complete all the tasks.

So, if the input is like tasks = [0, 1, 1, 2] k = 2, then the output will be 6, because first two tasks are of different type, so they can be executed without any gap, now at time 2, the next task is of same type task we have to wait for 2-time slot, then do the task and finally have other type task, type 2. So do this task. So it is like [0, 1, wait, wait, 1, 2]. From this we can identify, we need 6 time slots.

To solve this, we will follow these steps −

• tick := 0
• slot := a new map
• for each t in tasks, do
• tf := slot[t] if t is in slot
• if tf is not null and tf - tick > 0, then
• tick := tick + tf - tick
• tick := tick + 1
• slot[t] := tick + k
• return tick

Example

Let us see the following implementation to get better understanding −

def solve(tasks, k):
tick = 0
slot = {}
for t in tasks:
tf = slot.get(t)
if tf is not None and tf - tick > 0:
tick += tf - tick
tick += 1
slot[t] = tick + k

return tick

tasks = [0, 1, 1, 2]
k = 2
print(solve(tasks, k))

Input

[0, 1, 1, 2]


Output

6

Advertisements