Description
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.
Solution
DP, time O(n), space O(1)
簡單的dp題。如果用dp[n][2]表示每個房子rob與否,那么:
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]); // if don't rob i
dp[i][1] = num[i] + dp[i - 1][0] // if rob i
這樣其實可以簡單的降到O(1)空間,存儲兩個值即可。
class Solution {
public int rob(int[] nums) {
int ifRobbedPrev = 0;
int ifDidntRobPrev = 0;
for (int i = 0; i < nums.length; ++i) {
int tmp = ifDidntRobPrev;
ifDidntRobPrev = Math.max(ifDidntRobPrev, ifRobbedPrev);
ifRobbedPrev = nums[i] + tmp;
}
return Math.max(ifRobbedPrev, ifDidntRobPrev);
}
}