Skip to main content

Greedy Algorithms

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โ€‹

Greedy Strategy Overview Greedy Strategy GIF

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โ€‹

ProblemDifficultySolution
LC 455 โ€” Assign CookiesEasy
LC 55 โ€” Jump GameMedium
LC 45 โ€” Jump Game IIMedium
LC 435 โ€” Non-overlapping IntervalsMedium
LC 134 โ€” Gas StationMedium
LC 763 โ€” Partition LabelsMedium
LC 406 โ€” Queue Reconstruction by HeightMedium
LC 1005 โ€” Maximize Sum After K NegationsEasy
CC โ€” Good Sequences (CHEFSQ)Easy
CC โ€” Election Chips (ELECCHRP)Medium
LC 135 โ€” CandyHard
LC 122 โ€” Best Time to Buy and Sell Stock IIEasy
LC 860 โ€” Lemonade ChangeEasy
LC 944 โ€” Delete Columns to Make SortedEasy
LC 1221 โ€” Split a String in Balanced StringsEasy
LC 1710 โ€” Maximum Units on a TruckEasy
LC 11 โ€” Container With Most WaterMedium
LC 56 โ€” Merge IntervalsMedium
LC 452 โ€” Minimum Number of Arrows to Burst BalloonsMedium
LC 621 โ€” Task SchedulerMedium
LC 714 โ€” Best Time to Buy and Sell Stock with Transaction FeeMedium
LC 1029 โ€” Two City SchedulingMedium
LC 1247 โ€” Minimum Swaps to Make Strings EqualMedium
LC 1481 โ€” Least Number of Unique Integers after K RemovalsMedium
LC 1642 โ€” Furthest Building You Can ReachMedium
LC 1647 โ€” Minimum Deletions to Make Character Frequencies UniqueMedium
LC 1899 โ€” Merge Triplets to Form Target TripletMedium
CC โ€” Activity Selection (ACTSEL)Medium
CC โ€” Fractional Knapsack (FRACKNAP)Medium
LC 68 โ€” Text JustificationHard
LC 321 โ€” Create Maximum NumberHard
LC 330 โ€” Patching ArrayHard
LC 502 โ€” IPOHard
LC 630 โ€” Course Schedule IIIHard
LC 757 โ€” Set Intersection Size At Least TwoHard
LC 765 โ€” Couples Holding HandsHard
LC 968 โ€” Binary Tree CamerasHard
LC 1665 โ€” Minimum Initial Energy to Finish TasksHard
CC โ€” Job Sequencing (JOBSEQ)Hard
CC โ€” Advanced Greedy (ADVGREEDY)Hard

โ† Back to Home ยท ยฉ sparshjaswal