Maximum Profit in Job Scheduling
Hard
Topics
You are given n jobs, each described by a row [start, end, profit]. Taking a job earns its profit, but you can only work on one job at a time.
Two jobs may be taken together when they do not overlap. A job ending at time t and a job starting at time t do not overlap — the end is exclusive.
Return the maximum profit obtainable.
The judge names this argument grid, since it feeds every matrix problem through the same reader. It is the jobs table above, one row per job. LeetCode passes three parallel arrays instead.
Example 1
[start, end) window, and the end is exclusive — a job ending at time t and one starting at t can both be taken. The shaded set does not overlap anywhere and earns 120, which is the most available. Notice that the highest single profit is not always in it.Input: jobs = [[1,3,50],[2,4,10],[3,5,40],[3,6,70]] Output: 120 Explanation: Take [1,3) for 50 and [3,6) for 70. The 40 job also starts at 3 but pays less, and taking it would rule out the 70 one.
Example 2
Input: jobs = [[1,2,50],[3,5,20],[6,19,100]] Output: 170 Explanation: None of the three overlap, so all can be taken.
Example 3
Input: jobs = [[1,10,100],[2,3,10],[4,5,10]] Output: 100 Explanation: The long job blocks both short ones, and still beats their combined 20.
Constraints
- 1 <= n <= 5 * 10^4
- 1 <= start < end <= 10^9
- 1 <= profit <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Taking the most profitable job first is the natural guess and example 3 breaks it: the 100 job is the best single choice there and happens to be right, but shift the numbers slightly and a long expensive job can block two short ones worth more together.
The decision for one job depends only on what was possible before it starts, which suggests ordering the jobs by their end time. Processed in that order, the answer for "best profit using jobs that finish by time t" only ever grows, so each job can ask one question: what was the best profit available at the moment I start?
That question is a lookup into a table of (end time, best profit so far) that is already sorted by end time, so it is answered by searching for the latest end time that is at most this job’s start. Taking the job gives that profit plus its own; skipping it leaves the running best unchanged, and the larger of the two is recorded.
Approach
- Sort the jobs by end time.
- Keep a running table of
(endTime, bestProfit)pairs, starting with(0, 0). The profits in it are non-decreasing by construction. - For each job in order, find the last entry whose end time is
<=this job’s start, and read its profit. That is the best achievable before this job can begin. - The candidate is that profit plus this job’s profit. If it beats the table’s current best, append
(thisEnd, candidate); otherwise leave the table alone so it stays non-decreasing. - The last entry’s profit is the answer.
Walkthrough
jobs = [[1,3,50],[2,4,10],[3,5,40],[3,6,70]]
sorted by end: [1,3,50] [2,4,10] [3,5,40] [3,6,70]
job best before start candidate table (end,best)
(0,0)
[1,3,50] at time 1 -> 0 50 (0,0) (3,50)
[2,4,10] at time 2 -> 0 10 unchanged, 10 < 50
[3,5,40] at time 3 -> 50 90 (0,0) (3,50) (5,90)
[3,6,70] at time 3 -> 50 120 (0,0) (3,50) (5,90) (6,120)
answer 120
The [2,4,10] job is dropped not because 10 is small but
because nothing it could combine with beats what 50 already
achieved by the same time.Complexity
- Time — O(n log n): the sort, plus one search per job into a table that is already ordered.
- Space — O(n): the table holds at most one entry per job.
Common Pitfalls
- Sorting by start time. The table is built in end-time order, and sorting by start breaks the invariant that everything already in it has finished.
- Treating a job that starts exactly when another ends as an overlap. The end is exclusive, so those two are compatible, and a strict comparison in the search loses the pairing in example 1.
- Appending to the table unconditionally. Then the profits are no longer non-decreasing and the search returns a worse value than was actually available.
- Picking jobs greedily by profit, or by shortest duration. Neither is optimal.
mid = (lo + hi) / 2is the textbook form, and in Java or C++ it is the one that bites: the momentlo + hipasses2^31 - 1it wraps negative and the index flies out of range. This problem’s bounds never get close, so the code above is correct as written, butlo + (hi - lo) / 2is the habit worth keeping — same answer, same cost, no overflow. Python’s integers are arbitrary precision, so it is a non-issue there.
Full Solution — all languages
class Solution:
def jobScheduling(self, grid):
import bisect
jobs = sorted(grid, key=lambda job: job[1])
ends = [0]
best = [0]
for start, end, profit in jobs:
i = bisect.bisect_right(ends, start) - 1
candidate = best[i] + profit
if candidate > best[-1]:
ends.append(end)
best.append(candidate)
return best[-1]import java.util.*;
class Solution {
public int jobScheduling(int[][] grid) {
int[][] jobs = grid.clone();
Arrays.sort(jobs, (x, y) -> Integer.compare(x[1], y[1]));
List<Long> ends = new ArrayList<>(), best = new ArrayList<>();
ends.add(0L);
best.add(0L);
for (int[] job : jobs) {
long start = job[0], end = job[1], profit = job[2];
int lo = 0, hi = ends.size() - 1, at = 0;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (ends.get(mid) <= start) {
at = mid;
lo = mid + 1;
} else hi = mid - 1;
}
long candidate = best.get(at) + profit;
if (candidate > best.get(best.size() - 1)) {
ends.add(end);
best.add(candidate);
}
}
return (int) (long) best.get(best.size() - 1);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int jobScheduling(vector<vector<int>>& grid) {
vector<vector<int>> jobs = grid;
sort(jobs.begin(), jobs.end(), [](const vector<int>& x, const vector<int>& y) {
return x[1] < y[1];
})
;
vector<long long> ends {
0
},
best {
0
};
for (auto& job : jobs) {
long long start = job[0], end = job[1], profit = job[2];
int lo = 0, hi = (int)ends.size() - 1, at = 0;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (ends[mid] <= start) {
at = mid;
lo = mid + 1;
} else hi = mid - 1;
}
long long candidate = best[at] + profit;
if (candidate > best.back()) {
ends.push_back(end);
best.push_back(candidate);
}
}
return (int)best.back();
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var jobScheduling = function(grid) {
const jobs = grid.slice().sort((x, y) => x[1] - y[1]);
const ends = [0], best = [0];
for (const job of jobs) {
const start = job[0], end = job[1], profit = job[2];
let lo = 0, hi = ends.length - 1, at = 0;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (ends[mid] <= start) {
at = mid;
lo = mid + 1;
} else hi = mid - 1;
}
const candidate = best[at] + profit;
if (candidate > best[best.length - 1]) {
ends.push(end);
best.push(candidate);
}
}
return best[best.length - 1];
};