π‘ Greedy
One-line summary: Make the locally optimal choice at each step β works when local optima lead to a global optimum (proved by exchange argument).
Diagramβ
Conceptβ
A greedy algorithm: picks best available option, never backtracks. Works when greedy choice property + optimal substructure hold. When greedy fails, use DP.
Typically requires initial sorting. Time is usually O(n log n).
Common Patternsβ
Interval Scheduling (sort by end time)β
function maxNonOverlapping(intervals) {
intervals.sort((a, b) => a[1] - b[1]);
let count = 0,
lastEnd = -Infinity;
for (const [s, e] of intervals)
if (s >= lastEnd) {
count++;
lastEnd = e;
}
return count;
}
Jump Gameβ
function canJump(nums) {
let maxReach = 0;
for (let i = 0; i < nums.length; i++) {
if (i > maxReach) return false;
maxReach = Math.max(maxReach, i + nums[i]);
}
return true;
}
Pitfallsβ
- Greedy doesn't always work β verify with exchange argument or counterexample
- 0/1 Knapsack fails with greedy β use DP
- Greedy needs correct sorting criterion β wrong sort β wrong answer
Practice Problemsβ
Related Topicsβ
- Dynamic Programming β when greedy fails, DP is next
- Sorting β greedy often starts with a sort
β Back to Home Β· Β© sparshjaswal