House Robber
Aug 22, 2016
https://leetcode.com/problems/house-robber/
recursive function
Define rob(i, 1)
as the max money we can get if we rob the ith
house, rob(i, 0)
as max money we can get if we don’t rob ith house. Then:
|
|
Then, based on the idea above:
|
|
The complexity of this is O(2^n)
, which need be to optimized.
We can use dynamic programming to store the intermedia result by use a 2-D array:
int[][] dp = new int[nums.length][2]
dp[i][0] is for ith house, the max money we get if we don’t rob, dp[i][i]
as the max money we can get if we rob the house i;
dp[i][0] = Math.max(dp[i - 1][1], dp[i - 1][0]);
dp[i][1] = dp[i - 1][0] + nums[i];
further optimize
We don’t need a 2-D array to keep all the intermedia result for us, only the prevRob
and preNotRob
is needed.