Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Concept

Solving a Question with Dynamic Programming

State → recurrence → base case → order → answer
step 1 / 12
2
7
9
3
1
[0][1][2][3][4]
dp
·
·
·
·
·
[0][1][2][3][4]
The 5-step framework (House Robber)
1def rob(nums):
2 # 1. state: dp[i] = best loot using houses 0..i
3 # 2. recurrence: dp[i] = max(dp[i−1], dp[i−2] + nums[i])
4 # 3. base cases:
5 dp[0] = nums[0]
6 dp[1] = max(nums[0], nums[1])
7 # 4. order: left to right
8 for i in 2..n−1:
9 # skip house i, or rob it + best two back
10 dp[i] = max(dp[i−1], dp[i−2] + nums[i])
11 # 5. answer lives in the last cell
12 return dp[n−1]
state
  • problemHouse Robber
  • nums[2, 7, 9, 3, 1]

line 1Every DP boils down to FIVE questions. We will answer them on House Robber: along a street of houses you may not rob two ADJACENT houses; maximise the loot. The top row is nums; the dp row below is the table we will fill.