Course Schedule III
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Greedy.
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
Input: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]
Output: 3
Take course 1, 3, and 2.
Approach 1
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
⏱ O(2^N * N log N).💾 O(N)
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.
Approach 2
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
⏱ O(N^2).💾 O(N^2) or O(N).
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)
Approach 3
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
⏱ O(N log N).💾 O(N).
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
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.