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.
题目的含义是找数组中不相邻数字的最大总和,采用动态规划的思想,每一个位置决定是否偷,如果偷那么当前的dptake为上一步不偷+当前nums[i]的值,对应于dptake = temp + nums[i];如果不偷那么当前的dpnotake为上次偷或者不偷的最大值。
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if(n<0) return 0;
int dptake = 0;
int dpnotake = 0;
for(int i= 0;i<n;i++)
{
//当前不拿
int temp = dpnotake;
dpnotake = dptake>dpnotake?dptake:dpnotake;
dptake = temp + nums[i];
}
return dptake>dpnotake?dptake:dpnotake;
}
};