imashutosh51

Maximum Profit in Job Scheduling

Feb 8th, 2026
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. '''
  2. - First of all, sort the jobs by start time.
  3. - For every job, we have only two options:
  4.    1) Take the current job
  5.    2) Do not take the current job
  6.  
  7. - If we take the current job, then we cannot take any job that starts before the current job ends.
  8.  So instead of checking every future job, we directly jump to the next valid job.
  9.  
  10. - To find the next valid job:
  11.    - Create a sorted list of startTime from the sorted jobs.
  12.    - Use bisect_left on this startTime list with the current job's end time.
  13.    - This gives the index of the first job whose start time is >= current job's end time.
  14.  
  15. - Transition:
  16.    not_take = fun(i+1)
  17.    take = profit[i] + fun(next_idx)
  18.    dp[i] = max(take, not_take)
  19.  
  20. Trick:
  21. - First capsule (startTime, endTime, profit) into one list `jobs` and sort it.
  22. - Then extract startTime from the sorted jobs into a separate array for bisect_left.
  23. '''
  24.  
  25. from bisect import bisect_left
  26. def fun(i,dp,jobs,startTime):
  27.     if i==len(jobs):
  28.         return 0
  29.  
  30.     if dp[i]!=-1:
  31.         return dp[i]
  32.    
  33.     not_take_it=fun(i+1,dp,jobs,startTime)
  34.    
  35.     next_idx=bisect_left(startTime, jobs[i][1])
  36.     take_it=jobs[i][2]+fun(next_idx,dp,jobs,startTime)
  37.     dp[i]=max(not_take_it,take_it)
  38.     return dp[i]
  39.  
  40. class Solution:
  41.     def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
  42.         jobs=[]
  43.         for i in range(len(startTime)):
  44.             jobs.append([startTime[i],endTime[i],profit[i]])
  45.         jobs.sort()
  46.         startTime = [job[0] for job in jobs]
  47.  
  48.         n=len(startTime)
  49.         dp=[-1 for  i in range(len(startTime))]
  50.         fun(0,dp,jobs,startTime)
  51.         return max(dp)
  52.        
Advertisement
Add Comment
Please, Sign In to add comment