您的位置:首页 > 其它

Leetcode: House Robber

2015-08-05 22:00 399 查看

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题。不能同时取相邻的房子,那么到当前房子最大的值取决于它前3,前2的房子值,从中选择大的即可。

class Solution {
public:
int rob(vector<int>& nums) {
int max1 = 0;
int max2 = 0;
int max3 = 0;
for (int i = 0; i < nums.size(); ++i) {
int curMax = max(max1, max2) + nums[i];
max1 = max2;
max2 = max3;
max3 = curMax;
}

return max(max2, max3);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode dp