What is the difference between greedy algorithms and dynamic programming?

Answer

Both solve optimization problems, but they differ in when and how they make choices: Greedy algorithms: make the locally optimal choice at each step, hoping it leads to a globally optimal solution. Never reconsider previous choices. Only correct when the problem has the greedy choice property — a locally optimal choice is part of some globally optimal solution — AND optimal substructure. Time: usually O(n log n) or O(n). Examples: Dijkstra's (always expand closest node), Prim's/Kruskal's MST, Huffman encoding, Activity Selection, Fractional Knapsack. Greedy fails on: 0/1 Knapsack (fractional greedy doesn't work for integers), Coin Change with arbitrary denominations. Dynamic Programming: considers all possible choices and picks the best, using previously computed subproblems. Correct when the problem has overlapping subproblems + optimal substructure. Time: often O(n²) or O(n × capacity). Examples: 0/1 Knapsack, LCS, LIS, Edit Distance, Matrix Chain Multiplication. How to know which to use: (1) Try greedy — if you can prove it's always optimal (exchange argument), use it; (2) If greedy fails (can construct a counterexample), try DP; (3) Some problems need both (Dijkstra is greedy but relies on DP-like distance update). DP is a superset of greedy in a sense — greedy makes one choice, DP considers all.