1723. Find Minimum Time to Finish All Jobs

Description

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

Tags

Backtracking, Recursion

Solution

This page records a DFS solution. Check out Reference 2 for Dynamic Programming solution.

Apart from the minimum result ans (initialized with INT_MAX) and jobs, the DFS function also takes index idx for jobs and workload, which is an array with the length of k representing the working time of workers, as arguments. The edge case is when idx == len(jobs), we update the minimum ans. Iterate on workload (workers) and try to delegate job[idx] to workload[i], then search the (idx+1)th job through DFS, and then retract that job. Note that, if workload[i] == 0, we should break this loop since we only focus on Combination rather than Permutation. If we assign this job to the next worker instead, there will be duplicated computation.

Complexity

  • Time complexity: O(n×kn)O(n\times k^n)(to be comfirmed);

  • Space complexity: O(k)O(k), stacks cost by recursion.

Code

func minimumTimeRequired(jobs []int, k int) int {
	ans := 1 << 31
	dfs(&ans, 0, jobs, make([]int, k))
	return ans
}

func dfs(ans *int, idx int, jobs, workload []int) {
	if idx == len(jobs) {
		if m := maxInSlice(workload); m < *ans {
			*ans = m
		}
		return
	}
	for i := 0; i < len(workload); i++ {
		if workload[i]+jobs[idx] > *ans { // prune since it cannot be the optimal choice
			continue
		}
		workload[i] += jobs[idx]
		dfs(ans, idx+1, jobs, workload)
		workload[i] -= jobs[idx]
		if workload[i] == 0 { // we only focus on Combination rather than Permutation
			break
		}
	}
}

func maxInSlice(a []int) (m int) {
	for _, n := range a {
		if n > m {
			m = n
		}
	}
	return
}

Reference

Last updated

Was this helpful?