You are given an integer array jobs
, where jobs[i]
is the amount of time it takes to complete the ith
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 <= 12
1 <= jobs[i] <= 107
思路:
DFS+Prune
class Solution:
def minimumTimeRequired(self, jobs: List[int], k: int) -> int:
workers = [0]*k
self.res = sys.maxsize
# jobs.sort(reverse = True)
def dfs(curr):
if curr == len(jobs):
self.res = min(self.res, max(workers))
return
seen = set() # record searched workload of workers
for i in range(k):
if workers[i] in seen: continue # if we have searched the workload of 5, skip it.
if workers[i] + jobs[curr] >= self.res: continue # another branch cutting
seen.add(workers[i])
workers[i] += jobs[curr]
dfs(curr+1)
workers[i] -= jobs[curr]
dfs(0)
return self.res
二分+DFS+Prune
class Solution(object):
def minimumTimeRequired(self, jobs, K):
"""
:type jobs: List[int]
:type k: int
:rtype: int
"""
jobs.sort(reverse=True)
def ok(mid, status, s):
if s == len(jobs):
return True
for i in range(K):
if status[i]+jobs[s] <= mid:
status[i] += jobs[s]
if ok(mid, status, s+1):
return True
status[i] -= jobs[s]
if status[i] == 0:
return False
return False
lo,hi = 0,sum(jobs)
res = sum(jobs)
while lo<=hi:
mid = (lo+hi)//2
status = [0]*K
if ok(mid, status, 0):
res = mid
hi = mid-1
else:
lo = mid+1
return res
状压DP,Python会TLE,倒是学到了用 (t-1)& t 来求小于t的sub-binary string(原来是0的地方还是0)对应的值。比如6的二进制是110,小于6的sub-binary二进制是100,对应4 = 110 &(110-1)
class Solution(object):
def minimumTimeRequired(self, jobs, k):
"""
:type jobs: List[int]
:type k: int
:rtype: int
"""
n = len(jobs)
target = 1<<n
helper = [0] * target
for i in range(target):
for bit in range(n):
if (1<<bit) & i:
helper[i] += jobs[bit]
dp = [[0 for _ in range(target)] for _ in range(k)]
dp[0] = helper
for i in range(1, k):
for t in range(target):
dp[i][t] = dp[i-1][t]
s = t
while s:
dp[i][t] = min(dp[i][t], max(dp[i-1][t-s], helper[s]))
s = (s - 1) & t
return dp[-1][-1]