Given an array A and an integer H where and . Each element A[i] represents remaining pending jobs to be done and H represents hours left to complete all of the jobs. The task is to find the minimum speed in jobs per Hour at which person needs to work to complete all jobs in H hours.
Note: If A[i] has less job to be done than speed of person then he finish all of the work of A[i] and won’t go to next element during this hour.
Input: A = [3, 6, 7, 11], H = 8 Output: 4 Input: A = [30, 11, 23, 4, 20], H = 5 Output: 30
Approach: If the person can finish all the jobs (within H hours) with an speed of K jobs/hour then he can finish all jobs with a larger speed too.
If we let ispossible(K) be true if and only if the person can finish with a job speed of K, then there is some X such that ispossible(K) = True if and only if K >= X.
For example, with A = [3, 6, 7, 11] and H = 8, there is some X = 4 so that ispossible(1) = ispossible(2) = ispossible(3) = False, and ispossible(4) = ispossible(5) = … = True.
We can do a binary search on the values of ispossible(K) to find the first X such that ispossible(X) is True which will be our answer.
Now, as it is not allowed to move from one element to other during the current hour even if the job is completed than the maximum possible value of K can be the maximum element in the array A. So, to find the value of ispossible(K), (i.e. whether person with a job speed of K can finish all jobs in H hours), do binary search in the range (1, max_element_of_array).
Also, for each A[i] of jobs > 0, we can deduce that person finishes it in Math.ceil(A[i] / K) or ((A[i]-1) / K) + 1 hours, and we add these for all elements to find the total time to complete all of the jobs and compare it with H to check if it is possible to finish all jobs with a speed of K jobs/hour.
Below is the implementation of above approach:
Time Complexity: O(N*log(M)), where N is the length of array and M is max(A).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.