SDE & MLE Prep

1235. Maximum Profit in Job Scheduling

Problem

Job i runs from startTime[i] to endTime[i] and earns profit[i]. Choose jobs whose time ranges don't overlap (one may start exactly when another ends) to maximise the total profit.

Example: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70] → 120 (jobs 1 and 4)

Constraints: up to 5·10⁴ jobs.

Sort jobs by end time. dp[i] = best profit using the first i jobs = max(dp[i−1], profit[i] + dp[j]) where j = number of jobs ending ≤ start[i] (binary search).

jobs by end:  (1,3,50) (2,4,10) (3,5,40) (3,6,70)
dp:      0     50       50       90      120     <- 50 + 70

Complexity: O(n log n).

class Solution:
    def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
        jobs = sorted(zip(endTime, startTime, profit))
        ends = [e for e, _, _ in jobs]
        dp = [0] * (len(jobs) + 1)
        for i, (e, s, p) in enumerate(jobs, 1):
            j = bisect.bisect_right(ends, s, 0, i - 1)     # jobs finishing by time s
            dp[i] = max(dp[i - 1], dp[j] + p)
        return dp[-1]