Skip to content

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

 

Solutions

Solution: Backtracking

  • Time complexity: O(kn)
  • Space complexity: O(k)

 

JavaScript

js
/**
 * @param {number[]} jobs
 * @param {number} k
 * @return {number}
 */
const minimumTimeRequired = function (jobs, k) {
  const n = jobs.length;
  const workers = Array.from({ length: k }, () => 0);
  let result = Number.MAX_SAFE_INTEGER;

  jobs.sort((a, b) => b - a);

  const assignJob = (index, maxTime) => {
    if (maxTime >= result) return;
    if (index >= n) {
      result = Math.min(maxTime, result);
      return;
    }
    const time = jobs[index];

    for (let worker = 0; worker < k; worker++) {
      workers[worker] += time;

      const nextMaxTime = Math.max(workers[worker], maxTime);

      assignJob(index + 1, nextMaxTime);
      workers[worker] -= time;

      if (workers[worker] === 0) return;
    }
  };

  assignJob(0, 0);

  return result;
};

Released under the MIT license