【LeetCode】213. House Robber II
2015-07-03 17:22
302 查看
House Robber II
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
与House Robber的差异在于,nums[0]和nums[n-1]不能同时包含,
因此等同于nums[0...n-2]和nums[1...n-1]两者间取较大值。
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
与House Robber的差异在于,nums[0]和nums[n-1]不能同时包含,
因此等同于nums[0...n-2]和nums[1...n-1]两者间取较大值。
class Solution { public: int rob(vector<int>& nums) { if(nums.empty()) return 0; if(nums.size() == 1) return nums[0]; vector<int> nums1(nums); vector<int> nums2(nums); nums1.erase(nums1.begin()); nums2.pop_back(); return max(originRob(nums1), originRob(nums2)); } int originRob(vector<int>& nums) { if(nums.empty()) return 0; int prev2 = 0; int prev1 = nums[0]; for(int i = 1; i < nums.size(); i ++) { int cur = max(prev2+nums[i], prev1); prev2 = prev1; prev1 = cur; } return prev1; } };
相关文章推荐
- 定时器
- .net网站转到出错页是如何实现的
- 《图形学》实验三:DDA算法画直线
- AngularJs自定义指令详解(4) - transclude
- Algorithms—189.Rotate Array
- sdfasdfasdfasdfas
- jquery全选/取消全选(反选)/单选操作
- web扫描工具-Jsky使用
- [网站] ping 工具
- LinearLayout测量过程疑问
- 使用HTML打开本地应用
- 下拉刷新
- mybaits使用存储过程
- JavaScript事件
- UITextField的文本框部分文本以*的方式来显示
- GRE写作必备句型
- struct和union
- JS设计模式一:单例模式
- Android CheckBox中设置padding无效问题解决方法
- Dynamics AX 2012 - Report labels does not show up in report