LeetCode 213. House Robber II
2016-04-21 07:28
387 查看
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.
Since, the houses are surrounded like a circle. If we rob index 0, we can't rob index size - 1.
Take an example for break:
[4, 2, 3, 13, 8, 22]:
if I start robbing 4, the max would be 4 + 13 -> 17.
If I dont start robbing 4, the max would be 2+13+22 -> 37.
I thus separate the robbing into two cases:
1) start robbing at index 0, stop at size - 2;
2) start robbing at index 1, stop at size - 1.
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.
Since, the houses are surrounded like a circle. If we rob index 0, we can't rob index size - 1.
Take an example for break:
[4, 2, 3, 13, 8, 22]:
if I start robbing 4, the max would be 4 + 13 -> 17.
If I dont start robbing 4, the max would be 2+13+22 -> 37.
I thus separate the robbing into two cases:
1) start robbing at index 0, stop at size - 2;
2) start robbing at index 1, stop at size - 1.
int rob(vector<int>& nums) { if(nums.size() == 0) return 0; if(nums.size() == 1) return nums[0]; if(nums.size() == 2) return max(nums[0], nums[1]); vector<int> maxWithFirst(nums.size(), 0); vector<int> maxWithLast(nums.size(), 0); maxWithFirst[0] = nums[0]; maxWithFirst[1] = max(nums[0], nums[1]); maxWithLast[1] = nums[1]; maxWithLast[2] = max(nums[1], nums[2]); for(int i = 2; i < nums.size() - 1; ++i) { maxWithFirst[i] = max(nums[i] + maxWithFirst[i-2], maxWithFirst[i-1]); } for(int j = 3; j < nums.size(); ++j) maxWithLast[j] = max(nums[j] + maxWithLast[j-2], maxWithLast[j-1]); int n = nums.size(); return max(maxWithFirst[n - 2], maxWithLast[n - 1]); }
相关文章推荐
- NET工厂模式架构
- Javaweb微专业笔记开山篇---开发环境的搭建
- Android LayoutInflater详解
- Domain Model(领域模型)
- 站立会议 03
- 创业的第一百七十天
- 优麒麟 16.04 LTS 长期支持版发布
- 乱弹花絮-真正的爱情
- git回滚
- 第一次冲刺阶段第三天
- 第一次冲刺个人博客03
- 第一次冲刺站立会议03
- 浅谈java异常处理机制
- 如何批量删除织梦dede后台所有文章以及删除指定文章
- 关系型数据库工作原理-时间复杂度(翻译自Coding-Geek文章)
- CSS_腾讯QQ官网,新浪官网,网易官网,淘宝官网之css初始化代码
- 消息队列(RabbitMQ、zorneQ、metaQ、activeMQ)
- qq设计之 里氏替换原则
- HTTP1.1协议中文版-RFC2616
- 配置模型详解