1235. Maximum Profit in Job Scheduling
We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i]. You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range. If you choose a job that ends at time X you will be able to start another job that starts at time X.
Sort by start time
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
from collections import deque
from bisect import bisect_left, bisect_right
events = sorted(zip(startTime, endTime, profit))
dp = deque()
dp.appendleft((float('inf'), 0))
for i in range(len(events) - 1, -1, -1):
start, end, profit = events[i]
idx = bisect_left(dp, (end, -float('inf')))
if dp[idx][1] + profit > dp[0][1]:
dp.appendleft((start, dp[idx][1] + profit))
return dp[0][1]
Sort by end time
def jobScheduling(self, startTime, endTime, profit):
jobs = sorted(zip(startTime, endTime, profit), key=lambda v: v[1])
dp = [[0, 0]]
for s, e, p in jobs:
i = bisect.bisect_right(dp, [s, float('inf')]) - 1
i = min(i, len(dp) - 1)
if dp[i][1] + p > dp[-1][1]:
dp.append([e, dp[i][1] + p])
return dp[-1][1]