Pattern 06 / 10 · Advanced
Dynamic Programming
Solve each small case once, then build the big answer from the small ones.
The idea
Name the state (dp[i] = the best answer for the first i items), find how it depends on smaller states, and fill a table from the smallest case upward. Every state is computed once, so overlapping recursion turns into a single loop.
Reach for it when
- The question asks for a maximum, minimum or number of ways.
- A choice now depends on the best result of a smaller version of the problem.
- A plain recursion would solve the same subproblem many times.
Watch it run
198. House Robber
Houses in a row hold some money. You cannot rob two neighbours. Return the most you can rob.
Input: nums = [1, 2, 3, 1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
Input: nums = [2, 7, 9, 3, 1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
WALKTHROUGH INPUT · nums = [2, 7, 9, 3, 1]
houses (nums)
dp table
dp[i] = the most money from the first i houses. With no houses, dp[0] = 0.
1function rob(nums: number[]): number {2const dp = new Array(nums.length + 1).fill(0);3dp[1] = nums[0];4for (let i = 2; i <= nums.length; i++) {5const skip = dp[i - 1];6const take = dp[i - 2] + nums[i - 1];7dp[i] = Math.max(skip, take);8}9return dp[nums.length];10}