STOP 30 · DYNAMIC PROGRAMMING
Partitioning and Scheduling Optimization
Sort by end, binary search the last compatible job O(n log n)
- Learn first
- Leads to
- No later stop builds on it.
- How often asked
- No interview reports map onto this stop yet.
Warm up with this one
LC 983Minimum Cost For TicketsStuck? Peek at the approach
Choose passes with different coverage lengths on sparse travel dates and locate the next uncovered date.
Key points
- After sorting by end time, dp[i] is the best over the first i jobs; job i is either skipped or appended after the last job that doesn't overlap it.
- Find the last compatible job by binary searching the end times, for O(n log n) overall.
- "Split the array into k parts" problems usually use dp[parts][end] and enumerate where the last part starts.
Common pitfalls
- Whether touching endpoints conflict decides between upper_bound and lower_bound.
- Sorting by start time and greedily taking the highest profit fails once jobs carry weights.
- Sorting only the end times without moving the start times and profits along with them.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
Binary search · drop half each step
Find 23 in a sorted array
Try your own input
- Target
- 23
- left
- 0
- right
- 7
- mid
- —
The search range starts as the whole sorted array. The small numbers are indexes.
InvariantIf the target exists, it is always inside the closed range [left, right].
2D DP · filling the LCS table
Longest common subsequence of "ACBD" and "ABCD"
Try your own input
- LCS length
- —
dp[i][j] is the LCS length of the first i characters of "ACBD" and the first j of "ABCD". Row 0 and column 0 are empty strings: all 0.
InvariantRows fill left to right: when dp[i][j] is computed, the cells above, left and top-left are already final.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 983, with it.
Python
from bisect import bisect_right
def max_profit(start: list[int], end: list[int], profit: list[int]) -> int:
"""Best total profit of non-overlapping jobs; a job may start when another ends."""
jobs = sorted(zip(end, start, profit))
ends = [e for e, _, _ in jobs]
dp = [0] * (len(jobs) + 1) # dp[i]: best using the first i jobs by end time
for i, (_, s, p) in enumerate(jobs):
k = bisect_right(ends, s, 0, i) # jobs[:k] all end by time s
dp[i + 1] = max(dp[i], dp[k] + p) # skip job i, or take it after jobs[:k]
return dp[-1]C++
// Best total profit of non-overlapping jobs; a job may start when another ends.
long long maxProfit(const vector<int>& start, const vector<int>& end, const vector<int>& profit) {
int n = start.size();
vector<array<int, 3>> jobs(n); // {end, start, profit}
for (int i = 0; i < n; i++) jobs[i] = {end[i], start[i], profit[i]};
sort(jobs.begin(), jobs.end());
vector<long long> dp(n + 1, 0); // dp[i]: best using the first i jobs by end time
for (int i = 0; i < n; i++) {
auto [e, s, p] = jobs[i];
// k = number of earlier jobs that end by time s
int k = upper_bound(jobs.begin(), jobs.begin() + i, s,
[](int t, const array<int, 3>& job) { return t < job[0]; }) - jobs.begin();
dp[i + 1] = max(dp[i], dp[k] + p); // skip job i, or take it after the first k jobs
}
return dp[n];
}Java
class Solution {
// Best total profit of non-overlapping jobs; a job may start when another ends.
long maxProfit(int[] start, int[] end, int[] profit) {
int n = start.length;
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> Integer.compare(end[a], end[b]));
long[] dp = new long[n + 1]; // dp[i]: best using the first i jobs by end time
for (int i = 0; i < n; i++) {
int job = order[i];
int lo = 0, hi = i; // k = number of earlier jobs that end by start[job]
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (end[order[mid]] > start[job]) hi = mid;
else lo = mid + 1;
}
dp[i + 1] = Math.max(dp[i], dp[lo] + profit[job]); // skip it, or take it after them
}
return dp[n];
}
}Go
import "sort"
// maxProfit returns the best total profit of non-overlapping jobs; a job may
// start when another ends.
func maxProfit(start, end, profit []int) int {
n := len(start)
order := make([]int, n)
for i := range order {
order[i] = i
}
sort.Slice(order, func(a, b int) bool { return end[order[a]] < end[order[b]] })
dp := make([]int, n+1) // dp[i]: best using the first i jobs by end time
for i, job := range order {
// k = number of earlier jobs that end by start[job]
k := sort.Search(i, func(m int) bool { return end[order[m]] > start[job] })
dp[i+1] = max(dp[i], dp[k]+profit[job]) // skip it, or take it after them
}
return dp[n]
}Common variants
Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Day-indexed DP: a pass covering up to todayO(last day) time · O(last day) space
When the timeline is short and decisions are per day (1-, 7- or 30-day passes, day-by-day plans), dp[d] is the best up to day d: a day without travel copies yesterday, and a travel day tries each pass as the last one bought, covering today, coming from the day before it starts. LC 983 (Minimum Cost For Tickets); with a huge day range, jump between travel days and binary search the start.
Python
def min_ticket_cost(days: list[int], costs: list[int]) -> int:
"""Cheapest 1-, 7- and 30-day passes (prices costs) covering every travel day (LC 983)."""
travel = set(days)
last = days[-1]
dp = [0] * (last + 1) # dp[d]: cheapest cover of every travel day up to day d
for d in range(1, last + 1):
if d not in travel:
dp[d] = dp[d - 1] # nothing to cover today
continue
dp[d] = min(
dp[d - 1] + costs[0],
dp[max(0, d - 7)] + costs[1], # a 7-day pass ending today covers d-6..d
dp[max(0, d - 30)] + costs[2],
)
return dp[last]C++
// Cheapest 1-, 7- and 30-day passes (prices costs) covering every travel day (LC 983).
int minTicketCost(const vector<int>& days, const vector<int>& costs) {
int last = days.back();
vector<bool> travel(last + 1, false);
for (int d : days) travel[d] = true;
vector<int> dp(last + 1, 0); // dp[d]: cheapest cover of every travel day up to day d
for (int d = 1; d <= last; d++) {
if (!travel[d]) {
dp[d] = dp[d - 1]; // nothing to cover today
continue;
}
dp[d] = min({dp[d - 1] + costs[0],
dp[max(0, d - 7)] + costs[1], // a 7-day pass ending today covers d-6..d
dp[max(0, d - 30)] + costs[2]});
}
return dp[last];
}Java
class Solution {
// Cheapest 1-, 7- and 30-day passes (prices costs) covering every travel day (LC 983).
int minTicketCost(int[] days, int[] costs) {
int last = days[days.length - 1];
boolean[] travel = new boolean[last + 1];
for (int d : days) travel[d] = true;
int[] dp = new int[last + 1]; // dp[d]: cheapest cover of every travel day up to day d
for (int d = 1; d <= last; d++) {
if (!travel[d]) {
dp[d] = dp[d - 1]; // nothing to cover today
continue;
}
dp[d] = Math.min(dp[d - 1] + costs[0],
Math.min(dp[Math.max(0, d - 7)] + costs[1], // a 7-day pass ending today covers d-6..d
dp[Math.max(0, d - 30)] + costs[2]));
}
return dp[last];
}
}Go
// minTicketCost returns the cheapest 1-, 7- and 30-day passes covering every travel day (LC 983).
func minTicketCost(days, costs []int) int {
last := days[len(days)-1]
travel := make([]bool, last+1)
for _, d := range days {
travel[d] = true
}
dp := make([]int, last+1) // dp[d]: cheapest cover of every travel day up to day d
for d := 1; d <= last; d++ {
if !travel[d] {
dp[d] = dp[d-1] // nothing to cover today
continue
}
dp[d] = min(dp[d-1]+costs[0],
dp[max(0, d-7)]+costs[1], // a 7-day pass ending today covers d-6..d
dp[max(0, d-30)]+costs[2])
}
return dp[last]
}Backwards: solving one skips the next fewO(n) time · O(n) space
When taking item i forces you to skip the next few (questions that drain brainpower, tasks with cooldowns), compute dp[i], the best from i onwards, back to front: skipping gives dp[i + 1], taking gives the gain plus dp after the skip. Going backwards makes "where to land" a plain index. LC 2140 (Solving Questions With Brainpower).
Python
def most_points(questions: list[list[int]]) -> int:
"""questions[i] = [points, brainpower]; solving i skips the next brainpower ones (LC 2140)."""
n = len(questions)
dp = [0] * (n + 1) # dp[i]: best from question i on, filled back to front
for i in range(n - 1, -1, -1):
points, skip = questions[i]
dp[i] = max(dp[i + 1], points + dp[min(n, i + skip + 1)]) # pass on i, or solve it and jump
return dp[0]C++
// questions[i] = {points, brainpower}; solving i skips the next brainpower ones (LC 2140).
long long mostPoints(const vector<pair<int, int>>& questions) {
int n = questions.size();
vector<long long> dp(n + 1, 0); // dp[i]: best from question i on, filled back to front
for (int i = n - 1; i >= 0; i--) {
auto [points, skip] = questions[i];
dp[i] = max(dp[i + 1], points + dp[min(n, i + skip + 1)]); // pass on i, or solve it and jump
}
return dp[0];
}Java
class Solution {
// questions[i] = {points, brainpower}; solving i skips the next brainpower ones (LC 2140).
long mostPoints(int[][] questions) {
int n = questions.length;
long[] dp = new long[n + 1]; // dp[i]: best from question i on, filled back to front
for (int i = n - 1; i >= 0; i--)
dp[i] = Math.max(dp[i + 1], questions[i][0] + dp[Math.min(n, i + questions[i][1] + 1)]); // pass on i, or solve it and jump
return dp[0];
}
}Go
// mostPoints: questions[i] = {points, brainpower}; solving i skips the next brainpower ones (LC 2140).
func mostPoints(questions [][2]int) int {
n := len(questions)
dp := make([]int, n+1) // dp[i]: best from question i on, filled back to front
for i := n - 1; i >= 0; i-- {
points, skip := questions[i][0], questions[i][1]
dp[i] = max(dp[i+1], points+dp[min(n, i+skip+1)]) // pass on i, or solve it and jump
}
return dp[0]
}Why it works
- After sorting by end time, job i is either skipped (dp[i−1]) or taken; if taken, the jobs before it must end by its start, and those form a prefix of the sorted list, so the transition is dp[p] + profit.
- That the compatible jobs form a prefix relies on sorting by end time: end times are monotone, so binary search finds the last one ending at or before start[i].
- Unlike the unweighted greedy, an early-ending job is no longer always better once jobs have weights; the exchange argument fails, so DP has to compare taking and skipping.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
带权区间调度,我先按结束时间排序,dp[i] 表示前 i 个工作能拿到的最大收益。第 i 个工作要么不选,答案是 dp[i−1];要么选,就接在最后一个与它不重叠的工作后面。因为结束时间有序,与它兼容的工作正好是一个前缀,可以二分找到边界,所以整体 O(n log n)。带权之后贪心的交换论证不成立,这就是要用 DP 的原因。For weighted interval scheduling I sort by end time and let dp[i] be the best profit using the first i jobs. Job i is either skipped, giving dp[i − 1], or taken after the last job that does not overlap it. Because end times are sorted, the compatible jobs form a prefix, and binary search finds where it ends, so the whole thing is O(n log n). Once jobs carry weights the greedy exchange argument fails, which is why this needs DP.Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
Practice by stage
This stop's 6 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Core 5
| # | Problem | Approach | Rating |
|---|---|---|---|
| 983 | Minimum Cost For Tickets | Choose passes with different coverage lengths on sparse travel dates and locate the next uncovered date. | |
| 2140 | Solving Questions With Brainpower | Choose between skipping a question and taking its forced jump, practicing suffix DP with offset transitions. | |
| 1235 | Maximum Profit in Job Scheduling | Combine weighted interval selection with sorting, binary search, and DP, allowing jobs that meet exactly at endpoints. | |
| 2008 | Maximum Earnings From Taxi | Model ride earnings as weighted intervals, combining distance and tips and handling large total profits. | |
| 1043 | Partition Array for Maximum Sum | Enumerate the final segment while incrementally maintaining its maximum and enforcing the segment-length limit. |
Advanced 1
| # | Problem | Approach | Rating |
|---|---|---|---|
| 1335 | Minimum Difficulty of a Job Schedule | Partition by day count and prefix length, requiring at least one job per day and handling impossible schedules. |
OA questions on this topic 8
- Cinema ShowsAmazon
- Max Sum of Non-Overlapping IntervalsAmazon
- Minimum Weekly Input (Planning Campaingns :)Amazon
- Split Array Largest SumLinkedIn
- Maximum Order Volume (Weighted Interval Scheduling)Snowflake
- Minimize Total Input Cost (for LTMS)Salesforce
- Split Array Largest SumSalesforce
- Smart Gardener (Intuit India)Intuit