Greedy Algorithms

intermediate35 min

Greedy Algorithm Overview

Greedy picks the best-looking option at each step without revisiting earlier choices. When the problem has the right structure, that yields the global optimum in linear or linearithmic time; when it does not, you need DP or another approach.

When to Use Greedy

  • Optimal Substructure: Optimal solution contains optimal solutions to subproblems
  • Greedy Choice Property: Locally optimal choice leads to globally optimal solution
  • Simple Implementation: Often easier to implement than DP
  • Efficiency: Usually O(n log n) or O(n) time complexity

Activity Selection Problem

Fractional Knapsack

Huffman Coding

Common Greedy Problems

  • Scheduling: Activity selection, job scheduling
  • Knapsack: Fractional knapsack (0/1 knapsack is not greedy)
  • Compression: Huffman coding
  • Graph: Minimum spanning tree (Kruskal’s, Prim’s)
  • Coin Change: Making change with minimum coins (when greedy works)
  • Gas Station: Circular tour problem