Problem
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
1 |
|
Example 2:
1 |
|
Explanation 1
-
We can use dynamic programming to solve this problem.
-
Dynamic state is creating a one dimensional array
dp
.dp[i]
means the total maximum money when rob start from the first house to the indexi
house. -
Dynamic init. For example if
nums = [3, 2, 1, 5]
, then in index0dp[0] = 3
; then in index1,dp[1] = 3
because3 > 2
. -
Dyamic function. In index2, because we cannot rob the adjancent houses, so if we rob the current index2 house, then we cannot rob index1 house, in other word, if we rob index2, then
dp[2] = dp[0] + nums[2]
; if we don’t rob index2 house, thendp[2] = dp[1]
; so we can take the maximum of rob or not rob, which ismax(dp[0]+nums[2], dp[1])
. Therefore, dynamic function isdp[i] = max(dp[i-2] + nums[i], dp[i-1])
. -
Dynamic result is returning the last index of
dp
.
Solution 1
1 |
|
Explanation 2
-
We can save space by using four variables
rob
,notRob
,preRob
,preNotRob
. -
rob
andnotRob
means the current index house, we rob or notRob. -
preRob
andpreNotRob
means the at previous index house, we rob or notRob. -
If we rob the current index house, then we cannot rob the previous index house, which means
rob = nums[i] + preNotRob
. -
If we do not rob the current index house, then we can either rob the previous index house or don’t rob the previous hosue. We will take the maximum of these two.
-
In each iteration, we calculate
rob
andnotRob
. At the end of the iteration, we return the maximum ofrob
andnotRob
.
Solution 2
1 |
|