Skip to main content

Summary: Greedy Algorithms

Everything on one page, to review the chapter before moving on.

Key ideas​

  • Greedy algorithms build the solution step by step, taking the locally best choice according to a heuristic, and never reconsider a decision (The Greedy Method).
  • They are fast and simple, but their results depend on the heuristic: they may be optimal, merely good, or even fail to find a solution.
  • Their elements are the candidates and the selection, feasibility, solution and objective functions.
  • A single counterexample proves that a greedy algorithm is not optimal. Proving optimality needs the greedy choice property and optimal substructure, usually with an exchange argument.
  • When the selection takes candidates in a fixed order, the algorithm usually starts by sorting, and its cost is that of sorting.

At a glance​

ProblemHeuristicOptimal?Cost
Change (canonical coins, unlimited)Highest coin that fitsYesO(m)O(m), mm coin values
Change (any coins)Highest coin that fitsNoO(m)O(m)
Maximize the number of filesSmallest files firstYesO(nlog⁡n)O(n \log n)
Minimize free space on a diskLargest files firstNo—
Fractional knapsackHighest value per weight firstYesO(nlog⁡n)O(n \log n)
0/1 knapsackHighest value per weight firstNoO(nlog⁡n)O(n \log n)
One or several plumbersShortest tasks firstYesO(nlog⁡n)O(n \log n)
Knight's tourFewest onward jumps (Warnsdorff)Usually finds a tourO(n2)O(n^2)
Tasks to agentsCheapest per row or per columnSee the exercisesO(n2)O(n^2)
Graph coloringLowest available colorNoO(n2)O(n^2)
Minimum spanning treePrim: closest nodeYesO(n2)O(n^2) with a matrix, O(mlog⁡n)O(m \log n) with lists
Minimum spanning treeKruskal: cheapest edge without cycleYesSorting the edges + union-find

All the problems are in Classic Problems, except change, in The Greedy Method.

When to use it​

  • When a heuristic is provably optimal (canonical change, files, plumbers, minimum spanning trees, Dijkstra, Huffman).
  • When an approximate solution found fast is good enough.
  • As an initial bound for branch and bound, or as a heuristic to order the candidates in backtracking.
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.