Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 198 House Robber - Transition

The take-or-skip choice

2.2. Find the transition (the formula to compute each state)

Consider house at ii. You have two choices:

• If do not rob house ii, then the best answer using houses up to ii is the same as using houses up to i1i - 1: dp[i]=dp[i1].dp[i] = dp[i - 1].

• If do rob house ii, then you gain a[i]\text{a}[i] money, and you are not allowed to take money from house i1i - 1. The best rob from the remaining houses is dp[i2]dp[i - 2], so this option gives dp[i]=dp[i2]+a[i].dp[i] = dp[i - 2] + \text{a}[i].

So the recurrence is dp[i]=max(dp[i1], dp[i2]+a[i]).dp[i] = \max\bigl(dp[i - 1],\ dp[i - 2] + \text{a}[i]\bigr).

This way, calculate all the dp values. The only question left is: what is the final answer? You have established the recurrence. Now let us see the base cases.