Courses / DSA Patterns for Working Engineers / Chapter 14
Module 4 · Binary search, subsets, greedy, backtracking and DP · Chapter 14 of 39
Dynamic Programming: States, Transitions and Tables
Builds on Greedy Techniques: Safe Local Choices and How to Prove Them and Backtracking: Choose, Explore, Undo and Prune. Next up: Cyclic Sort: Placing Each Value at Its Own Index.
Part 1 · Introduction to dynamic programming
What dynamic programming is
A shelf fitter wants to know in how many ways a shelf can be filled with planks, and plain recursion needs over 58 crore calls for a shelf only 40 cm long.
Dynamic programming, usually shortened to DP, solves a problem by combining the answers to smaller problems of the same kind, and solving each distinct smaller problem once. Two properties make it work.
- Optimal substructure: the answer to the whole problem can be built from answers to its parts.
- Overlapping subproblems: the same part is needed again and again, so remembering its answer saves work.
Divide and conquer, like merge sort, splits a problem into parts that do not overlap, so there is nothing to remember. A greedy algorithm commits to one choice. DP tries every choice at each step, but never solves the same subproblem twice, which often turns an exponential search into a polynomial one.
Every DP solution is described by four parts, and writing them down before any code is the habit that prevents most mistakes.