๐ก 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