leetcode House Robber II
2015-06-21 21:12
417 查看
题目
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.
题目来源:https://leetcode.com/problems/house-robber-ii/
分析
上一个题house robber的解析见:/article/2077171.html这个题在上一道题的基础上加了一个限制条件,也就是首和尾也是相邻的。那就拆开做,分别去掉第一个元素和最后一个元素后再用第一道题的方案去求解。最大值就是本题的答案。
代码
[code]class Solution { public: int rob1(vector<int>& nums, int begin, int end) { int size = end - begin + 1; if(size == 1) return nums[begin]; vector<int> dp(size + 1, 0); dp[size-1] = nums[end]; int ans = dp[size - 1]; int max_next = 0; for(int i = end - 1; i >= begin; i--){ dp[i - begin] = nums[i] + max_next; ans = max(ans, dp[i - begin]); max_next = max(dp[i - begin +1], max_next); } return ans; } int rob(vector<int>& nums) { int len = nums.size(); if(len == 0) return 0; if(len == 1) return nums[0]; return max(rob1(nums, 0, len - 2), rob1(nums, 1, len - 1)); } };
相关文章推荐
- .toString和String.valueOf()
- PS-
- HDU-5273
- 团队作业-第五周-测试与调试
- ubuntu平台hadoop2.6.0安装Hbase
- Tmux 速成教程:技巧和调整
- java基础—IO流——字节流的操作演示
- 【华为oj】字符串运用-密码截取
- ios开发-多线程GCD之详解
- java学习之旅01--如何学习
- ubuntu-查看iso文件的md5
- 《人,绩效和职业道德》与博客文章的读后感
- 谈谈Ext JS组件之引子
- JAVA类型修饰符(public,protected,private,friendly)
- [C#]剖析异步编程语法糖: async和await
- [Leetcode.python] 001. Two Sum
- Redis测井系统
- 【机房收费个人版】DataTable 与泛型集合的较量
- I Hate It
- 比一比 WebService和WCF