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.
每个房子有一定的钱,相邻房子不能同时被抢,如何最大化收益。
简单DP,记录到每个位置时的最大收益,那么dp[i] = max(dp[i-1], dp[i-2] nums[i]),即取抢和不抢的最大值。
因为只和前面两个状态有关,因此又可以对空间复杂度进行优化,用两个变量分别表示前一个位置和再前面一个位置的最大值。
代码语言:javascript复制class Solution {
public:
int rob(vector<int>& nums) {
int a = 0;
int b = 0;
for(int i = 0; i < nums.size(); i )
{
if(i&1)
a = max(a nums[i], b);
else
b = max(a, b nums[i]);
}
return max(a, b);
}
};