Skip to main content

πŸ’‘ 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​

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