Course Schedule III
Master this topic with zero to advance depth.
Course Schedule III
Take maximum number of courses given [duration, lastDay] constraints.
Visual Representation
Courses: [[100, 200], [1000, 1250], [200, 1300]]
1. [100, 200] -> time=100. Heap: [100].
2. [1000, 1250] -> time=1100. Heap: [100, 1000].
3. [200, 1300] -> time=1300. Heap: [100, 200, 1000].
Result: 3Examples
Take course 1, 3, and 2.
Level I: Recursive Backtracking
Intuition
Try all possible subsets of courses. For each subset, check if there exists an ordering that satisfies all deadlines. The maximum subset size that works is the answer.
Thought Process
- Generate all subsets of courses.
- For each subset, sort it by deadline and check if it's feasible.
- Return the maximum feasible subset size.
Pattern: Brute Force / Subsets
Detailed Dry Run
[[100,200], [1000, 1250], [200, 1300]]
- Try subset [[100,200], [200,1300]]: Feasible? 100<=200 (Y), 300<=1300 (Y). Size 2.
- Try subset [[100,200], [1000,1250], [200,1300]]: Feasible? 100<=200, 1100<=1250, 1300<=1300. YES. Size 3.
Level II: Dynamic Programming
Intuition
This can be viewed as an 0/1 Knapsack problem where the 'weight' is the duration and the 'limit' is the deadline. We sort by deadline first to ensure we process courses in an order that respects feasibility.
Thought Process
- Sort courses by
lastDay. dp[i][t]= max courses among firstithat can be finished by timet.- This is still too slow (). A better DP is
dp[i][j]= min time to finishjcourses using firsticourses.
Pattern: Dynamic Programming
Detailed Dry Run
Sorted: [[100,200], [200, 1300]] dp[0][0]=0, dp[0][1]=100 (others inf) dp[1][0]=0, dp[1][1]=min(100, 200)=100, dp[1][2]=100+200=300 (300<=1300? Yes)
Level III: Optimal Greedy (Max-Heap + Retroactive Swap)
Intuition
Process courses by deadline. If a course doesn't fit, replace the longest course already taken with this shorter one to save time.
Thought Process
- Sort by
lastDay. - Maintain
timeand a Max-Heap of durations. - Add current duration to
timeand heap. - If
time > lastDay, subtract the max duration fromtime(pop heap).
Pattern: Greedy with Retroactive Swap
Detailed Dry Run
[[100, 200], [500, 600], [200, 600]]
- [100, 200]: time=100, heap=[100]
- [500, 600]: time=600, heap=[500, 100]
- [200, 600]: time=800 > 600. Pop 500. time=300, heap=[200, 100] Result: 2
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.