Dynamic Programming21 sections · 915 units
Open in Course

LeetCode 198 House Robber - Final Answer

Reading the answer

3.3. Determine the final answer

You process all values from 22 up to nn using the formula dp[i]=max⁡(dp[i−1], dp[i−2]+a[i]),for i=2,3,…,n.dp[i] = \max\bigl(dp[i - 1],\ dp[i - 2] + \text{a}[i]\bigr), \quad \text{for } i = 2, 3, \dots, n. The final answer to the problem is simply dp[n].dp[n]. This dynamic programming solution runs in O(n)O(n) time and uses O(n)O(n) space, and it uses O(n)O(n) memory.**

The structure is exactly the same: define the state (what each dp[i] represents), find the transition, set the base cases, and read the final answer from the appropriate dpdp state.