liveBook · Manning

Greedy algorithm

As explained in Advanced Algorithms and Data Structures

A solution method that repeatedly makes the locally best available choice according to a specified ranking or criterion.

A greedy algorithm repeatedly chooses the best immediate option according to a criterion. That local choice can produce an optimal answer for some problems, but it can also miss the best overall solution or serve only as an approximation. section 1.3.2

Check whether the local choice fits the problem’s constraints:

  • For 0-1 knapsack, choosing food by highest calories or calories per kilogram can block a better combination. section 1.3.2
  • For fractional knapsack, sorting by calories per kilogram and taking a fraction of the last item fills the capacity with the best total described. section 1.3.4
  • Dijkstra’s algorithm chooses the closest unvisited vertex; negative-weight edges break the assumption that this choice fixes its minimum distance. section 14.4.4
Table 1.2 The list in table 1.1, sorted by calories per kg (view table figure)

Food

Weight (kgs)

Total calories

Calories per kg

Peanut butter

20

117,800

5,890

Rice

300

1,122,000

3,740

Wheat flour

400

1,444,000

3,610

Strawberry jam

50

130,000

2,600

Beans (can)

300

690,000

2,300

Potatoes

800

1,501,600

1,877

Tomatoes (can)

300

237,000

790

The food table ranks items by calories per kilogram, the criterion used for the fractional-knapsack strategy. section 1.3.4

Greedy methods apply only when the problem supports their local choices. When it does not, consider another approach: Bellman-Ford handles negative-weight edges, while brute force or dynamic programming can address the 0-1 knapsack problem. section 14.4.4 section 1.3.5

How Advanced Algorithms and Data Structures covers it

How deep it goes
Defines local choice and illustrates where it succeeds or fails, without giving a general proof technique.
Examples
Compares food packing by calories or calories per kilogram with shortest-route selection and local optimization.
What you can do after
Evaluate whether a locally best choice fits a problem’s constraints before relying on a greedy solution.
How it connects
Connects greedy algorithms to knapsack problems, Dijkstra’s algorithm, breadth-first search, Bellman-Ford, and dynamic programming.

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 Advanced Algorithms and Data Structures. The section links point to the parts of the book it draws on.