Maximum Profit in Job Scheduling (LeetCode 1235): Solution and Explanation
Each job has a start time, an end time and a profit. Pick a set of jobs that never overlap in time and maximize the total profit. A job may start at exactly the moment another one ends.
Watch it run step by step
Try your own input and write the code →Intuition
This is weighted interval scheduling. The unweighted version, where every job is worth the same, has a greedy answer: always take the job that finishes first. Weights break that greedy, since one long valuable job can beat three short cheap ones. Trying every subset of jobs is O(2^n), so we need a way to make each job's decision depend on a small amount of state.
Sort jobs by start time and think about job i as the first job we are deciding on. We either skip it, in which case the best we can do is the best answer for jobs i + 1 onward, or we take it, in which case we earn its profit and then jump to the first job that starts at or after job i ends. Every job between those two overlaps job i, so it is ruled out. That gives dp[i] = max(dp[i + 1], profit[i] + dp[next(i)]), which only looks to the right, so we fill dp from the last job back to the first.
The only remaining cost is finding next(i). Because jobs are sorted by start time, the start times form a sorted array, and the first job with start at least end[i] can be found by binary search. That keeps each transition at O(log n) and the whole algorithm at O(n log n).
Approach: Sort, DP from the right, binary search
- Zip the three arrays into
(start, end, profit)tuples and sort them by start time. - Create
dpof size n + 1, wheredp[i]is the best profit using only jobs i through n - 1 anddp[n] = 0. - Write
findNext(i), a binary search over indicesi + 1tonfor the first job whose start is at leastjobs[i][1]. - Iterate
ifrom n - 1 down to 0. - Compute
take = jobs[i][2] + dp[findNext(i)]andskip = dp[i + 1], and storedp[i] = max(take, skip). - Return
dp[0].
Step-by-step example
startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
- Sorted jobs are (1,3,50), (2,4,10), (3,5,40), (3,6,70), and
dp[4] = 0. - i = 3: the job ends at 6 and no later job starts at 6 or after, so next is 4. take = 70, skip = 0,
dp[3] = 70. - i = 2: ends at 5, next is 4. take = 40, skip = 70,
dp[2] = 70. - i = 1: ends at 4, next is 4. take = 10, skip = 70,
dp[1] = 70. - i = 0: ends at 3, and the first job starting at or after 3 is index 2. take = 50 +
dp[2]= 120, skip = 70, sodp[0] = 120. - The answer is 120, from jobs (1,3,50) and (3,6,70).
Code: Python, Java, C++
1class Solution:
2 def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
3 jobs = sorted(zip(startTime, endTime, profit))
4 n = len(jobs)
5
6 # dp[i] = max profit considering jobs from i to n-1
7 dp = [0] * (n + 1)
8
9 # Binary search for next non-overlapping job
10 def findNext(i):
11 target = jobs[i][1] # end time of current job
12 lo, hi = i + 1, n
13 while lo < hi:
14 mid = (lo + hi) // 2
15 if jobs[mid][0] >= target:
16 hi = mid
17 else:
18 lo = mid + 1
19 return lo
20
21 # Process jobs from right to left
22 for i in range(n - 1, -1, -1):
23 nextJob = findNext(i)
24 # Take or skip current job
25 take = jobs[i][2] + dp[nextJob]
26 skip = dp[i + 1]
27 dp[i] = max(take, skip)
28
29 return dp[0]1class Solution {
2 public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
3 int n = startTime.length;
4 int[][] jobs = new int[n][3];
5 for (int i = 0; i < n; i++) {
6 jobs[i] = new int[]{startTime[i], endTime[i], profit[i]};
7 }
8 Arrays.sort(jobs, (a, b) -> a[0] - b[0]);
9
10 int[] dp = new int[n + 1];
11
12 for (int i = n - 1; i >= 0; i--) {
13 int nextJob = findNext(jobs, i);
14 int take = jobs[i][2] + dp[nextJob];
15 int skip = dp[i + 1];
16 dp[i] = Math.max(take, skip);
17 }
18
19 return dp[0];
20 }
21
22 private int findNext(int[][] jobs, int i) {
23 int target = jobs[i][1];
24 int lo = i + 1, hi = jobs.length;
25 while (lo < hi) {
26 int mid = (lo + hi) / 2;
27 if (jobs[mid][0] >= target) hi = mid;
28 else lo = mid + 1;
29 }
30 return lo;
31 }
32}1class Solution {
2public:
3 int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
4 int n = startTime.size();
5 vector<array<int, 3>> jobs(n);
6 for (int i = 0; i < n; i++) {
7 jobs[i] = {startTime[i], endTime[i], profit[i]};
8 }
9 sort(jobs.begin(), jobs.end());
10
11 vector<int> dp(n + 1, 0);
12
13 for (int i = n - 1; i >= 0; i--) {
14 int target = jobs[i][1];
15 int lo = i + 1, hi = n;
16 while (lo < hi) {
17 int mid = (lo + hi) / 2;
18 if (jobs[mid][0] >= target) hi = mid;
19 else lo = mid + 1;
20 }
21 int take = jobs[i][2] + dp[lo];
22 int skip = dp[i + 1];
23 dp[i] = max(take, skip);
24 }
25
26 return dp[0];
27 }
28};Time and space complexity
O(n log n)
Sorting costs O(n log n), and each of the n DP steps runs one binary search costing O(log n).
O(n)
The sorted job list and the dp array each have O(n) entries.
Other approaches
Sort by end time with a forward DP (time O(n log n), space O(n))
Sort by end time and let dp[i] be the best profit among the first i jobs. For job i, binary search the last job that ends at or before its start and take the better of skipping or adding its profit. It is the textbook weighted interval scheduling form and is equally fast.
Heap of finished jobs (time O(n log n), space O(n))
Process jobs by start time and keep a min heap of (end, accumulated profit). Before handling a job, pop every entry that has ended and track the best profit seen so far. It avoids writing a binary search but is a little harder to prove correct.
Common mistakes
- Using
>instead of>=in the binary search, which wrongly forbids a job starting exactly when the previous one ends. - Applying the unweighted greedy of picking the earliest finishing job, which ignores profits and gives wrong answers.
- Sorting the three arrays separately, which breaks the link between each job's start, end and profit.
- Sizing
dpas n instead of n + 1. When no compatible job exists,findNextreturns n, so the sentineldp[n] = 0must be there to read.
Frequently asked questions
Why does Maximum Profit in Job Scheduling need dynamic programming?
Picking jobs greedily by end time or by profit fails once jobs have different values. The DP compares taking and skipping each job, which accounts for every trade-off while sharing work across subproblems.
Why is binary search used?
After sorting by start time, the start times are increasing, so the first job compatible with job i is a lower bound search. That replaces a linear scan and brings the total down to O(n log n).
Can a job start at the same time another ends?
Yes. Touching endpoints do not count as overlapping here, which is why the search uses start >= end.