Find Minimum Time to Finish All Jobs Problem
Description
LeetCode Problem 1723.
You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the i^th job.
There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.
Return the minimum possible maximum working time of any assignment.
Example 1:
Input: jobs = [3,2,3], k = 3
Output: 3
Explanation: By assigning each person one job, the maximum time is 3.
Example 2:
Input: jobs = [1,2,4,7,8], k = 2
Output: 11
Explanation: Assign the jobs the following way:
Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)
Worker 2: 4, 7 (working time = 4 + 7 = 11)
The maximum working time is 11.
Constraints:
1 <= k <= jobs.length <= 121 <= jobs[i] <= 10^7
Solution
Approach: Backtracking with Pruning
Assign each job to one of the k workers and minimise the largest load. Trying every assignment costs k^n, so we cut the search:
- Sort the jobs in descending order, so large jobs are placed first and bad branches show up early.
- Keep the best answer found so far; abandon a branch as soon as some worker's load reaches it.
- If a worker has no job yet, try only the first such worker for the current job, since all empty workers are interchangeable.
The depth-first search puts the current job on a worker, recurses to the next job, and then undoes the choice.
Complexity: O(k^n) time in the worst case, though the pruning makes it far faster in practice, and O(n + k) space.
from math import inf
class Solution:
def minimumTimeRequired(self, jobs: List[int], k: int) -> int:
def dfs(i):
nonlocal ans
if i == len(jobs):
ans = min(ans, max(cnt))
return
for j in range(k):
if cnt[j] + jobs[i] >= ans:
continue
cnt[j] += jobs[i]
dfs(i + 1)
cnt[j] -= jobs[i]
if cnt[j] == 0:
break
cnt = [0] * k
jobs.sort(reverse=True)
ans = inf
dfs(0)
return ans