Algorithm patterns← All patterns

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.

time O(n) here; O(states × choices) in generalspace O(n), often O(1) with two variables

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.

Example 1

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.

Example 2

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)

2
0
7
1
9
2
3
3
1
4

dp table

0
0
·
1
·
2
·
3
·
4
·
5
skip = –take = –

dp[i] = the most money from the first i houses. With no houses, dp[0] = 0.

1 / 11
solution.ts
1function rob(nums: number[]): number {
2 const dp = new Array(nums.length + 1).fill(0);
3 dp[1] = nums[0];
4 for (let i = 2; i <= nums.length; i++) {
5 const skip = dp[i - 1];
6 const take = dp[i - 2] + nums[i - 1];
7 dp[i] = Math.max(skip, take);
8 }
9 return dp[nums.length];
10}

Practice next