1235. Maximum Profit in Job Scheduling
Asked at 23Amazon51Bloomberg34Microsoft33Google25Meta15Airbnb93Pony.ai100Verkada91Snowflake81PhonePe78DoorDash77WeRide68Meesho67Docusign64Swiggy59Palo Alto Networks50ByteDance50Pinterest44Oracle41Uber35Goldman Sachs33Infosys30TikTok26
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]
assert Solution().jobScheduling([1, 2, 3, 3], [3, 4, 5, 6], [50, 10, 40, 70]) == 120
assert Solution().jobScheduling([1, 2, 3, 4, 6], [3, 5, 10, 6, 9], [20, 20, 100, 70, 60]) == 150
assert Solution().jobScheduling([1, 1, 1], [2, 3, 4], [5, 6, 4]) == 6
class Solution {
public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
int n = startTime.length;
Integer[] idx = new Integer[n];
for (int i = 0; i < n; i++) idx[i] = i;
Arrays.sort(idx, (a, b) -> endTime[a] - endTime[b]);
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
int job = idx[i - 1], s = startTime[job];
int lo = 0, hi = i - 1; // count of jobs among first i-1 ending <= s
while (lo < hi) {
int mid = (lo + hi) / 2;
if (endTime[idx[mid]] <= s) lo = mid + 1; else hi = mid;
}
dp[i] = Math.max(dp[i - 1], dp[lo] + profit[job]);
}
return dp[n];
}
}
func jobScheduling(startTime []int, endTime []int, profit []int) int {
n := len(startTime)
idx := make([]int, n)
for i := range idx {
idx[i] = i
}
sort.Slice(idx, func(a, b int) bool { return endTime[idx[a]] < endTime[idx[b]] })
ends := make([]int, n)
for i, j := range idx {
ends[i] = endTime[j]
}
dp := make([]int, n+1) // dp[i] = best profit using the first i jobs by end time
for i := 1; i <= n; i++ {
job := idx[i-1]
// jobs among the first i-1 that finish by this job's start
j := sort.Search(i-1, func(k int) bool { return ends[k] > startTime[job] })
dp[i] = max(dp[i-1], dp[j]+profit[job])
}
return dp[n]
}