# Program to schedule tasks to take smallest amount of time in Python

Suppose we have a list of values called tasks where each different value represents a different task type, and we also have a non-negative integer k. Each task wants one minute to complete, but we must wait k minutes between doing two tasks of the same type. At any time, we can be doing a task or waiting. We have to find the smallest amount of time it takes to complete all the tasks.

So, if the input is like nums = [2, 2, 2, 3, 3, 2], k = 1, then the output will be 7, as the optimal ordering is [2, 3, 2, 3, 2, WAITING, 2].

To solve this, we will follow these steps −

• c := count of all values in nums

• ans := 0, lastsize := 0

• while c is non−zero, do

• lastsize := size of c

• for each value x in most common (k + 1) values of c, do

• c[x] := c[x] − 1

• if c[x] is same as 0, then

• remove c[x]

• ans := ans + k + 1

• return ans + lastsize - (k + 1)

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, nums, k):
from collections import Counter
c = Counter(nums)
ans = 0
lastsize = 0
while c:
lastsize = len(c)
for x, _ in c.most_common(k + 1):
c[x] -= 1
if c[x] == 0:
del c[x]
ans += k + 1
return ans + lastsize - (k + 1)
ob1 = Solution()
nums = [2, 2, 2, 3, 3, 2]
k = 1
print(ob1.solve(nums, k))

## Input

[2, 2, 2, 3, 3, 2], 1

## Output

7

Updated on: 21-Oct-2020

138 Views