After robbing those houses on that street, the thief have found himself a new place for his thievery so that he would not GE T too much attention. This time, all houses at the is arranged in a circle. That's means the first house was 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 in each house, determine the maximum amount of mone Y you can rob tonight without alerting the police.
Notice
This is a extension of house robber.
Example
Nums = [3,6,4], return 6
Leetcode on the original topic, please see my previous blog house robber Ii.
Solution One:
classSolution { Public: /** * @param nums:an array of non-negative integers. * Return:the maximum amount of money can rob tonight*/ intHouseRobber2 (vector<int>&nums) { if(Nums.size () <=1)returnNums.empty ()?0: nums[0]; Vector<int> A = nums, B =Nums; A.erase (A.begin ()); B.pop_back (); returnMax (Rob (a), Rob (b)); } intRob (vector<int> &nums) { if(Nums.size () <=1)returnNums.empty ()?0: nums[0]; Vector<int> dp{nums[0], Max (nums[0], nums[1])}; for(inti =2; I < nums.size (); ++i) {dp.push_back (max (Dp[i-2] + nums[i], dp[i-1])); } returnDp.back (); }};
Solution Two:
classSolution { Public: /** * @param nums:an array of non-negative integers. * Return:the maximum amount of money can rob tonight*/ intHouseRobber2 (vector<int>&nums) { if(Nums.size () <=1)returnNums.empty ()?0: nums[0]; returnMax (Rob (Nums,0, Nums.size ()-1), Rob (Nums,1, Nums.size ())); } intRob (vector<int> &nums,intLeftintRight ) { intA =0, B =0; for(inti = left; I < right; ++i) {intm = A, n =b; A= n +Nums[i]; b=Max (M, n); } returnMax (A, b); }};
[Lintcode] House Robber II Dagujieshe two