liveBook · Manning

Greedy algorithm

As explained in Fabulous Adventures in Data Structures and Algorithms

A greedy algorithm constructs a solution by repeatedly choosing the locally best available option without generally reconsidering earlier choices.

A greedy algorithm breaks a large problem into smaller subproblems, chooses an optimal solution for each, and combines those choices. Because each choice is made for its subproblem rather than the whole problem, the combined result can be suboptimal. section 9.2

Making change

For 73 cents in US coins, choosing the largest available coin first yields two quarters, two dimes, and three pennies: seven coins. But without nickels, the same strategy makes 41 cents with eight coins; four dimes and a penny needs only five. Greedy choices can be quick and useful, but need not be globally optimal. section 9.2

Pretty printers use greedy algorithms to reformat code quickly, where an acceptable result may be preferable to waiting for an optimal one. section 9.0 section 9.2

How Fabulous Adventures in Data Structures and Algorithms covers it

How deep it goes
Defines subproblem optimization and demonstrates its trade-off with successful and failing change-making cases.
Examples
Uses US coin change for 73 cents and 41 cents without nickels, alongside source-code pretty printing.
What you can do after
Evaluate whether a fast greedy solution is acceptable by comparing it with a slower optimal alternative.
How it connects
Connects greedy algorithms to change-making, backtracking, and pretty printing.

Also explained in

Compare how 12 books explain greedy algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fabulous Adventures in Data Structures and Algorithms. The section links point to the parts of the book it draws on.