STOP 08 · LINEAR STRUCTURES
Greedy Algorithms and Scheduling
Sort by end time, keep what fits O(n log n) time
- Learn first
- Leads to
- No later stop builds on it.
Warm up with this one
LC 455Assign CookiesStuck? Peek at the approach
Sort demands and resources, satisfying the smallest remaining demand with the smallest usable resource.
Key points
- Always take the interval that ends first; it leaves the most room. Exchange argument: the first pick of any optimal answer can be swapped for it without loss.
- Minimum removals = total minus the maximum kept; "minimum arrows" is the same loop, except that touching endpoints count as overlapping.
- Before writing a greedy, state why the local choice never hurts; if you can't, the problem probably needs DP.
Common pitfalls
- Sorting by start time lets one long interval that starts early block everything else.
- Whether touching endpoints overlap depends on the problem; >= versus > is one character and a different answer.
- A comparator written as a[1] - b[1] overflows near ±2^31.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
Interval greedy · keep the earliest finish
How many intervals can you keep with no overlap (touching ends are fine)?
Try your own input
- Kept
- 0
- Last end
- −∞
The intervals are sorted by right end; each row of the chart is one interval.
InvariantExchange argument: the first interval of any optimal answer can be swapped for the one that ends first, with no loss.
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 455, with it.
Python
def max_non_overlapping(intervals: list[list[int]]) -> int:
"""Most intervals you can keep with no overlap; [a, b] and [b, c] may touch."""
count, end = 0, float("-inf")
for start, finish in sorted(intervals, key=lambda iv: iv[1]):
if start >= end: # fits after the last kept interval
count += 1
end = finish
return countC++
// Most intervals you can keep with no overlap; [a, b] and [b, c] may touch.
int maxNonOverlapping(vector<vector<int>> intervals) {
sort(intervals.begin(), intervals.end(),
[](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; });
int count = 0;
long long end = LLONG_MIN;
for (auto& iv : intervals)
if (iv[0] >= end) { // fits after the last kept interval
count++;
end = iv[1];
}
return count;
}Java
class Solution {
// Most intervals you can keep with no overlap; [a, b] and [b, c] may touch.
int maxNonOverlapping(int[][] intervals) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int count = 0;
long end = Long.MIN_VALUE;
for (int[] iv : intervals)
if (iv[0] >= end) { // fits after the last kept interval
count++;
end = iv[1];
}
return count;
}
}Go
import (
"math"
"sort"
)
// maxNonOverlapping returns the most intervals you can keep with no overlap;
// [a, b] and [b, c] may touch.
func maxNonOverlapping(intervals [][]int) int {
sort.Slice(intervals, func(i, j int) bool { return intervals[i][1] < intervals[j][1] })
count, end := 0, math.MinInt
for _, iv := range intervals {
if iv[0] >= end { // fits after the last kept interval
count++
end = iv[1]
}
}
return count
}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.
Reach frontier: jump level by levelO(n) time · O(1) space
When each position says how far it can jump and the question is whether the end is reachable or how few jumps it takes: track how far the next jump could reach, and when i hits the current jump's boundary, count a jump and move the boundary there. It is BFS without a queue. LC 45 (Jump Game II); LC 55 only checks that the reach never falls behind i.
Python
def min_jumps(nums: list[int]) -> int:
"""Fewest jumps from index 0 to the last; nums[i] is the longest jump from i (LC 45)."""
jumps = end = far = 0 # indexes up to end take `jumps` jumps; far: the next jump's reach
for i in range(len(nums) - 1):
far = max(far, i + nums[i])
if i == end: # this jump's range is used up: take another
jumps += 1
end = far
return jumpsC++
// Fewest jumps from index 0 to the last; nums[i] is the longest jump from i (LC 45).
int minJumps(const vector<int>& nums) {
int jumps = 0, end = 0, far = 0; // indexes up to end take `jumps` jumps; far: the next jump's reach
for (int i = 0; i + 1 < (int)nums.size(); i++) {
far = max(far, i + nums[i]);
if (i == end) { // this jump's range is used up: take another
jumps++;
end = far;
}
}
return jumps;
}Java
class Solution {
// Fewest jumps from index 0 to the last; nums[i] is the longest jump from i (LC 45).
int minJumps(int[] nums) {
int jumps = 0, end = 0, far = 0; // indexes up to end take `jumps` jumps; far: the next jump's reach
for (int i = 0; i + 1 < nums.length; i++) {
far = Math.max(far, i + nums[i]);
if (i == end) { // this jump's range is used up: take another
jumps++;
end = far;
}
}
return jumps;
}
}Go
// minJumps returns the fewest jumps from index 0 to the last; nums[i] is the longest jump from i.
func minJumps(nums []int) int {
jumps, end, far := 0, 0, 0 // indexes up to end take `jumps` jumps; far: the next jump's reach
for i := 0; i+1 < len(nums); i++ {
far = max(far, i+nums[i])
if i == end { // this jump's range is used up: take another
jumps++
end = far
}
}
return jumps
}Regret heap: take it, then drop the worst when overO(n log n) time · O(n) space
Scan by deadline (or position), take each item at first, and when a limit is broken, drop the costliest item taken so far, found in O(log n) with a heap. LC 630 (Course Schedule III), LC 1642 (Furthest Building You Can Reach) and LC 871 (Minimum Number of Refueling Stops) are this take-back greedy.
Python
import heapq
def schedule_course(courses: list[list[int]]) -> int:
"""Most courses [duration, last day] you can finish one at a time (LC 630)."""
taken: list[int] = [] # chosen durations as a max-heap (negated)
day = 0
for duration, last in sorted(courses, key=lambda c: c[1]): # earliest deadline first
heapq.heappush(taken, -duration)
day += duration
if day > last: # past the deadline: drop the longest course taken so far
day += heapq.heappop(taken)
return len(taken)C++
// Most courses {duration, last day} you can finish one at a time (LC 630).
int scheduleCourse(vector<pair<int, int>> courses) {
sort(courses.begin(), courses.end(), [](auto& a, auto& b) { return a.second < b.second; }); // earliest deadline first
priority_queue<int> taken; // chosen durations, longest on top
long long day = 0;
for (auto [duration, last] : courses) {
taken.push(duration);
day += duration;
if (day > last) { // past the deadline: drop the longest course taken so far
day -= taken.top();
taken.pop();
}
}
return taken.size();
}Java
class Solution {
// Most courses {duration, last day} you can finish one at a time (LC 630).
int scheduleCourse(int[][] courses) {
int[][] sorted = courses.clone();
Arrays.sort(sorted, Comparator.comparingInt(c -> c[1])); // earliest deadline first
PriorityQueue<Integer> taken = new PriorityQueue<>(Comparator.reverseOrder()); // longest on top
long day = 0;
for (int[] c : sorted) {
taken.offer(c[0]);
day += c[0];
if (day > c[1]) day -= taken.poll(); // past the deadline: drop the longest course taken so far
}
return taken.size();
}
}Go
import (
"container/heap"
"sort"
)
// maxHeap is a max-heap of ints for container/heap.
type maxHeap []int
func (h maxHeap) Len() int { return len(h) }
func (h maxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h maxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *maxHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *maxHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
// scheduleCourse returns the most courses {duration, last day} you can finish one at a time (LC 630).
func scheduleCourse(courses [][2]int) int {
sorted := append([][2]int(nil), courses...)
sort.Slice(sorted, func(i, j int) bool { return sorted[i][1] < sorted[j][1] }) // earliest deadline first
taken := &maxHeap{} // chosen durations, longest on top
day := 0
for _, c := range sorted {
heap.Push(taken, c[0])
day += c[0]
if day > c[1] { // past the deadline: drop the longest course taken so far
day -= heap.Pop(taken).(int)
}
}
return taken.Len()
}Why it works
- Exchange argument: let o be the earliest-ending interval in an optimal answer and g the earliest-ending interval overall, the one greedy picks, so g.end ≤ o.end. Swapping o for g keeps the rest compatible, since they all start after o.end and hence after g.end, and the count is unchanged.
- Induction: after the swap, what is left is the same problem on the intervals that start after g.end, so the same argument applies to the rest.
- Sorting by start or by length both fail: with [1,10], [2,3], [4,5], start order keeps only one; with [1,5], [4,7], [6,10], taking the shortest [4,7] first also keeps only one, while two is possible in both.
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.
选最多的不重叠区间,我按结束时间排序,能放就放。理由是交换论证:最优解里结束最早的那个区间,总可以换成我选的这个结束更早的区间,后面的区间不受影响,数量不变。换完后剩下的是同样的问题,归纳下去就证明了贪心最优。排序 O(n log n),扫描 O(n);按开始时间或长度排序都有反例。To keep the most non-overlapping intervals, I sort by end time and take each interval that fits. The exchange argument says the earliest-ending interval of any optimal answer can be swapped for mine, which ends no later, without breaking the rest or changing the count. What remains is the same problem, so induction shows greedy is optimal. Sorting costs O(n log n) and the scan O(n), and sorting by start or by length both have counterexamples.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 25 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Foundation 2
| # | Problem | Approach | Rating |
|---|---|---|---|
| 455 | Assign Cookies | Sort demands and resources, satisfying the smallest remaining demand with the smallest usable resource. | |
| 1338 | Reduce Array Size to The Half | Remove values in descending frequency order to minimize the number of types needed to halve the array. |
Core 17
| # | Problem | Approach | Rating |
|---|---|---|---|
| 55 | Jump Game | Maintain the furthest reachable position and stop when the current position falls outside that range. | |
| 45 | Jump Game II | Count jumps by advancing the boundary of the current reachable layer instead of choosing the largest local jump. | |
| 134 | Gas Station | Eliminate starting candidates using deficit intervals and also check whether the total fuel is sufficient. | |
| 135 | Candy | Satisfy left and right neighbor constraints separately, then combine each position's minimum requirements. | |
| 763 | Partition Labels | Use each character's last occurrence to identify partition boundaries that cannot be split further. | |
| 179 | Largest Number | Define a sorting comparator through the two concatenation orders and handle an all-zero result. | |
| 1029 | Two City Scheduling | Start from a common baseline cost and sort reassignment differences while meeting both cities' headcount constraints. | |
| 621 | Task Scheduler | Analyze the cooling gaps created by the most frequent tasks and compare the formula with heap simulation. | |
| 767 | Reorganize String | Choose the most frequent remaining character different from the previous one and check whether construction is possible. | |
| 1405 | Longest Happy String | Choose the highest remaining frequency without creating three equal consecutive characters, switching to the next choice when necessary. | |
| 881 | Boats to Save People | The heaviest person needs a boat; test whether the lightest can join to justify the two-pointer strategy. | |
| 870 | Advantage Shuffle | Win with the smallest sufficient value when possible; otherwise sacrifice the smallest value to preserve stronger ones. | |
| 948 | Bag of Tokens | Buy points at low energy cost and sell high-value tokens for energy, keeping track of the best score reached. | |
| 945 | Minimum Increment to Make Array Unique | After sorting, raise each value to at least one more than its predecessor and accumulate the minimum increments. | |
| 1007 | Minimum Domino Rotations For Equal Row | Test only the two values on the first domino, then count the fewest rotations to align one side. | |
| 826 | Most Profit Assigning Work | Sort workers by ability, scan feasible jobs, and maintain the highest available profit. | |
| 1642 | Furthest Building You Can Reach | Reserve limited ladders for the largest climbs, using a heap to revise resource assignments dynamically. |
Advanced 6
| # | Problem | Approach | Rating |
|---|---|---|---|
| 678 | Valid Parenthesis String | Maintain a range of possible unmatched-opening counts instead of enumerating the three meanings of every star. | |
| 630 | Course Schedule III | Schedule by deadline and remove the longest course when time runs out to preserve capacity for later courses. | |
| 871 | Minimum Number of Refueling Stops | Extend the reachable range and, when fuel is insufficient, choose the largest supply from stations already passed. | |
| 502 | IPO | Unlock projects by required capital, then choose the highest-profit project currently available. | |
| 857 | Minimum Cost to Hire K Workers | Enumerate the maximum wage-to-quality ratio and minimize the selected group's total quality to reduce cost. | |
| 1383 | Maximum Performance of a Team | Scan by the minimum efficiency and maintain the speed sum of at most k workers to maximize performance. |
OA questions on this topic 285
- Group StudentsAmazon
- Cart Prefix ZeroAmazon
- Get Score DifferenceAmazon
- Get Winner CountAmazon
- Find Longest RegexAmazon
- Get Minimum Pen Drive SizeAmazon
- Get Max ThroughputAmazon
- Find Max Value (Matrix Compression)Amazon
- Get Minimum Health (Armor Round)Amazon
- Find Optimal PermutationAmazon