smj007

Maximum Profit in job scheduling

Aug 21st, 2025
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. from typing import List
  2. import bisect
  3.  
  4. class Solution:
  5.     def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
  6.        
  7.         # Step 1: Combine start, end, profit into a single jobs list
  8.         jobs = []
  9.         for s, e, p in zip(startTime, endTime, profit):
  10.             jobs.append((s, e, p))
  11.  
  12.         # Step 2: Sort jobs by end time (important for DP ordering)
  13.         jobs.sort(key=lambda x: x[1])
  14.  
  15.         # Step 3: Extract the list of end times (for binary search later)
  16.         ends = [e for _, e, _ in jobs]
  17.  
  18.         # Helper function: find index of last job that does NOT overlap
  19.         # For a given job starting at "start", we want the rightmost job whose end <= start
  20.         def get_non_overlapping_job(start, ends):
  21.             return bisect.bisect_right(ends, start) - 1
  22.  
  23.         # Step 4: DP array where dp[i] = max profit we can earn by considering first i jobs
  24.         dp = [0] * (len(jobs) + 1)
  25.  
  26.         # Step 5: Process jobs in order of end time
  27.         for i in range(1, len(jobs) + 1):
  28.             start, end, profit = jobs[i-1]
  29.  
  30.             # Find last non-overlapping job index
  31.             j = get_non_overlapping_job(start, ends)
  32.  
  33.             # Option 1: skip current job → dp[i-1]
  34.             # Option 2: take current job → profit + dp[j+1]
  35.             dp[i] = max(dp[i-1], profit + dp[j+1])
  36.  
  37.         # Step 6: Final answer is max profit after considering all jobs
  38.         return dp[len(jobs)]
  39.  
Advertisement
Add Comment
Please, Sign In to add comment