Find minimum speed to finish all Jobs in C++


In this problem, we are given an array arr[] consisting of n elements and an integer h. Each element of the array arr[] contains the number of pending jobs for the person and H is the time left to complete the jobs (in Hours). Our task is to Find minimum speed to finish all Jobs.

Problem Description: We need to find the number of jobs the person needs to complete in one hour in order to complete all the jobs given in the array in H hours. If he can complete all specified at arr[i] in less than an hour, we will sit ideally for the rest of the time and after the end of the hour, move to the next set of jobs.

Let’s take an example to understand the problem,

Input

arr[] = {4, 5, 1, 7, 8}, H = 5

Output

8

Explanation

The person needs to complete 5 sets of jobs in 5 hours. So, he/She needs to perform the set with the maximum number of jobs in 1 hours which will be his/her speed.

Solution Approach

To solve the problem, we need to find the minimum speed with which he can perform all the tasks. So, we will find the first value for which the person can do all tasks is the given amount of time.

We will search for the speed within the range 1 to max no. of jobs to do in one go. As this value can be large, we will use binary search for ease of computation.

To check, if at the current speed s, the person can solve the problem, we will find the time taken to complete one set and then add the time for all sets. If this time is less than H, then it is possible otherwise not.

Program to illustrate the working of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool canDoJobInTime(int A[], int n, int H, int speed) {
   int timeTaken = 0;
   for (int i = 0; i < n; ++i)
      timeTaken += (A[i] - 1) / speed + 1;
   return timeTaken <= H;
}
int calcJobMinSpeed(int A[], int n, int H) {
   if (H < n)
      return -1;
   int maxJob = A[0];
   for(int i = 1; i < n; i++)
      maxJob = max(A[i], maxJob);
   int start = 1, end = maxJob;
   while (start < end) {
      int mi = start + (end - start) / 2;
      if (!canDoJobInTime(A, n, H, mi))
         start = mi + 1;
      else
         end = mi;
   }
   return start;
}
int main() {
   int A[] = { 3, 6, 7, 11 }, H = 8;
   int n = sizeof(A) / sizeof(A[0]);
   cout<<"The minimum speed to finish all jobs in time is "<<calcJobMinSpeed(A, n, H);
   return 0;
}

Output

The minimum speed to finish all jobs in time is 4

Updated on: 12-Mar-2021

104 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements