Learn about algorithms that make locally optimal choices at each step to solve optimization problems efficiently in various contexts.
A greedy algorithm constructs a solution by choosing at each step the option that seems best at that moment, without backtracking. It is simple and fast, and for certain problems it yields the optimum; for others it only provides a good approximation [1].
A problem is suitable for a greedy solution when it has two properties: the greedy choice property (there exists an optimum that includes the locally best choice) and optimal substructure (after the choice, the remainder is the same problem, but smaller). This is usually proven with an exchange argument: every optimal solution can be modified to include the greedy choice without worsening it [1][2].
With coins of $1$, $5$, $10$, and $25$ cents, for $63$ cents you first take $25$, then again $25$, then $10$ and three of $1$: in total $6$ coins, which is the minimum (calculation, assumed values). For this coin system the greedy is optimal.
With coins of $1$, $3$, and $4$ and amount $6$, the greedy chooses $4 + 1 + 1$, that is $3$ coins, while the optimum is $3 + 3$, that is $2$ coins (calculation). The locally best choice, the largest coin, does not lead to the optimum. In these cases dynamic programming is needed.
- Activity selection: among activities with start and finish times, always choose the one that finishes first; maximizes the number of compatible activities.
- Minimum spanning trees: Kruskal’s and Prim’s algorithms (see the dedicated lines).
- Shortest paths with nonnegative weights: Dijkstra (see the dedicated line).
- Huffman coding: repeatedly merge the two least frequent symbols.
Often the cost is dominated by a sort or a priority queue: $O(n \log n)$. Compared to exhaustive methods this is a huge saving.
Data compression, networks, scheduling, and approximation algorithms for NP-hard problems, such as set cover (see the line on NP-hard problems) (general remark).
Greedy is not always optimal and must be justified for each problem. A wrong choice early on cannot be corrected. For problems like 0-1 knapsack it gives approximate solutions, and should be compared with dynamic programming or exact methods.
[1] Wikipedia (it): Algoritmo greedy
[2] Wikipedia (en): Greedy algorithm
Generating summary…