Find minimum time to finish all jobs with given constraints in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of jobs with different time requirements, there are k different persons to assign jobs and we also have how much time t an assignee takes to do one unit of the job. We have to find the minimum time to complete all jobs with following constraints.

  • An assignee can be assigned only the contiguous jobs.

  • Two assignees cannot share or perform a single job.

So, if the input is like k = 4, t = 5, job = {12, 6, 9, 15, 5, 9}, then the output will be 75 as we get this time by assigning [12],[6, 9],[15] and [5, 9]

To solve this, we will follow these steps −

  • Define a function is_valid() . This will take time, K, job

  • n := size of job

  • count := 1, curr_time := 0, i := 0

  • while i < n, do

    • if curr_time + job[i] > time, then

      • curr_time := 0

      • count := count + 1

    • otherwise,

      • curr_time := curr_time + job[i]

      • i := i + 1

  • return true when count <= K

  • From the main method, do the following <

  • n := size of job

  • end := 0, begin := 0

  • for i in range 0 to n, do

    • end := end + job[i]

  • res := end

  • job_max := maximum of job

  • while begin <= end, do

    • mid := ((begin + end) / 2) take integer part

    • if mid >= job_max and is_valid(mid, K, job) is true, then

      • res := minimum of res, mid

      • end := mid - 1

    • otherwise,

      • begin := mid + 1

  • return res * T

Example

Let us see the following implementation to get better understanding −

 Live Demo

def is_valid(time, K, job):
   n = len(job)
   count = 1
   curr_time = 0
   i = 0
   while i < n:
      if curr_time + job[i] > time:
         curr_time = 0
         count += 1
      else:
         curr_time += job[i]
         i += 1
   return count <= K
def get_minimum_time(K, T, job):
   n = len(job)
   end = 0
   begin = 0
   for i in range(n):
      end += job[i]
   res = end
   job_max = max(job)
   while begin <= end:
      mid = int((begin + end) / 2)
      if mid >= job_max and is_valid(mid, K, job):
         res = min(res, mid)
         end = mid - 1
      else:
         begin = mid + 1
   return res * T
job = [12, 6, 9, 15, 5, 9]
k = 4
T = 5
print(get_minimum_time(k, T, job))

Input

4, 5, [12, 6, 9, 15, 5, 9]

Output

75
raja
Published on 25-Aug-2020 11:33:34
Advertisements