Find Minimum Time to Finish All Jobs

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:


Solution:

2 optimazations:

1. start from most time consuming jobs
2. assign a job to free works only once


class Solution {
    public int minimumTimeRequired(int[] jobs, int k) {
        Arrays.sort(jobs); // opt 1
        int left = 1, right = Integer.MAX_VALUE;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            int[] caps = new int[k];
            Arrays.fill(caps, mid);
            if (canFinish(jobs, jobs.length - 1, caps, k, mid)) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
    
    private boolean canFinish(int[] jobs, int i, int[] caps, int k, int cap) {
        if (i == -1) return true;
        for (int j = 0; j < k; j ++) {
            if (caps[j] >= jobs[i]) {
                caps[j] -= jobs[i];
                if (canFinish(jobs, i - 1, caps, k, cap)) {
                    return true;
                }
                caps[j] += jobs[i];
            }
            if (caps[j] == cap) break;  // opt 2
        }
        return false;
    }
}