Maximum Profit in Job Scheduling (LeetCode 1235): Solution and Explanation

Hard
Array
Binary Search
Dynamic Programming
Sorting

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Zip the three arrays into (start, end, profit) tuples and sort them by start time.
  2. Create dp of size n + 1, where dp[i] is the best profit using only jobs i through n - 1 and dp[n] = 0.
  3. Write findNext(i), a binary search over indices i + 1 to n for the first job whose start is at least jobs[i][1].
  4. Iterate i from n - 1 down to 0.
  5. Compute take = jobs[i][2] + dp[findNext(i)] and skip = dp[i + 1], and store dp[i] = max(take, skip).
  6. Return dp[0].

Step-by-step example

startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
  1. Sorted jobs are (1,3,50), (2,4,10), (3,5,40), (3,6,70), and dp[4] = 0.
  2. 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.
  3. i = 2: ends at 5, next is 4. take = 40, skip = 70, dp[2] = 70.
  4. i = 1: ends at 4, next is 4. take = 10, skip = 70, dp[1] = 70.
  5. i = 0: ends at 3, and the first job starting at or after 3 is index 2. take = 50 + dp[2] = 120, skip = 70, so dp[0] = 120.
  6. 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]

Time and space complexity

Time

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).

Space

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 dp as n instead of n + 1. When no compatible job exists, findNext returns n, so the sentinel dp[n] = 0 must 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.