Greedy Algorithm

  • Greedy algorithms are applied to optimization algorithms only.

  • It picks always the current best solution; no backtracking.

  • Not necessarily optimal --> need to prove it.

Optimization Problem

  • find a set of items that can

    • meet some constraints, and

    • optimize some objective function

  • examples: shortest path, minimum spanning tree

  • not an optimization problem: sorting

Prove the Optimality

To prove the optimality of a greedy strategy, we need to prove the following two parts.

  • Greedy Choice

    • find the choice that is part of SOME optimal solution

    • there may exist multiple optimal solutions; no need to prove it for ANY optimal solution

  • Optimal Substructure

    • After making the first choice, the final best solution is first choice + best solution for the rest of (compatible) input

    • We can solve the same optimization problem recursively!

    • Otherwise, we find a contradiction!

Example problems

  • activity selection (pick the earliest-finish task)

  • minimum spanning tree

  • Huffman code

  • Dijkastra's shortest path

  • graph coloring

  • traveling salesman

Greedy vs. Dynamic Programming

  • Greedy: always pick the current best

  • DP: pick the best based on history

  • You can always use DP to solve Activity Selection problem, but it is much costly (since you have to try all other branches)

Example Code: Easy Swaps to Sort 123

Last updated