Greedy algorithm
A greedy algorithm solves optimization problems by picking, at each decision, the option that looks best at that moment. The idea is to reach the best overall result through good local choices. In coin change: with the pending amount, you take the largest coin that does not go over, and repeat. For 31 with coins of 1, 5, 10 and 20: 20, 10 and 1, 3 coins.
Greedy and dynamic programming both solve optimization problems and both use optimal substructure, but they work differently. Dynamic programming, at each stage, looks at every possible earlier decision and builds the solution from the subproblems'. Greedy moves forward without reconsidering anything: each choice shrinks the remaining problem, until it is done. That is why it is faster: greedy coin change costs O(amt / min(coins)) against O(n × amt).
Solving with greedy takes 3 steps. Analyze the problem: states, objective and constraints. Choose the greedy strategy: how each step chooses, shrinking what is left. And prove it is correct, almost always by contradiction or induction. Choosing the strategy is the hard part: it varies a lot between problems, and some look right but fail in certain cases, like coin change.
There are classic problems solved with greedy. Scheduling tasks: always picking the one that ends first gives the most tasks. Fractional knapsack: take the highest value per kilo first. Buying and selling stock with several trades. Huffman coding: always merge the 2 least frequent nodes to compress without loss. And Dijkstra's algorithm, which finds the shortest paths in graphs with nonnegative weights.
