Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 198 House Robber - Defining the DP

Setting up the state

1.1. Define the state: Let dp[i]dp[i] = the maximum money you can steal from houses 11 through ii. With this definition, you know the best outcome at each position without committing to whether you rob the last house.

For a=[2,7,9,3,1]a = [2, 7, 9, 3, 1]: dp[1]=2dp[1] = 2, dp[2]=7dp[2] = 7 (take house 22 alone), dp[3]=11dp[3] = 11 (take houses 11 and 33: 2+9=112 + 9 = 11). The state at position ii depends only on earlier positions, so you can fill the table left to right using a simple recurrence.