# Program to find minimum time to finish all jobs in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called jobs, where jobs[i] indicates the amount of time needed to complete the ith job. We also have another value k, to them we can assign jobs. Each job should be assigned to exactly one worker. And the working time of a worker is the total time it takes to complete all jobs assigned to them. We have to find the minimum possible maximum working time of any assignment.

So, if the input is like jobs = [2,1,3,8,5], k = 2, then the output will be 10 because, we can assign jobs like:

• Worker1: 2 + 5 + 3 = 10

• Worker2: 1 + 8 = 9

So maximum time is 10.

To solve this, we will follow these steps −

• sort the list jobs in reverse order

• assign := list of first k jobs

• jobs := list of remaining jobs

• Define a function dp() . This will take i, assign

• if i is same as size of jobs , then

• return maximum of assign

• ans := infinity

• for x in range 0 to k - 1, do

• assign := a new list from assign

• assign[x] := assign[x] + jobs[i]

• ans := minimum of ans and dp(i+1, assign)

• assign[x] := assign[x] - jobs[i]

• return ans

• from the main method return dp(0, assign)

## Example

Let us see the following implementation to get better understanding

def solve(jobs, k):
jobs.sort(reverse=True)
assign = tuple(jobs[:k])
jobs = jobs[k:]

def dp(i, assign):
if i == len(jobs):
return max(assign)

ans = float('inf')
for x in range(k):
assign = list(assign)
assign[x] += jobs[i]
ans = min(ans, dp(i+1, tuple(assign)))
assign[x] -= jobs[i]

return ans

return dp(0, assign)

jobs = [2,1,3,8,5]
k = 2
print(solve(jobs, k))

## Input

[2,1,3,8,5], 2


## Output

10
Published on 07-Oct-2021 08:49:16