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.
//和上一题类似,只是多了一个“环”的条件,就是抢了第一家,就不能抢最后一家 //分别计算抢第二家到最后一家与抢第一家到倒数第二家的最大值,取两个值中更大的那个就是结果。 class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); if (n == 0) return 0; if (n == 1) return nums[0]; int* dp = new int[n + 1]; //抢第一家到倒数第二家得到的金钱最大值 dp[0] = nums[0]; for (int i = 1; i < n-1 ; ++i){ dp[i] = max(dp[i - 1], (i==1? 0: dp[i-2])+nums[i] ); } int res1=dp[n-2]; //抢第二家到最后一家得到的金钱最大值 dp[1] = nums[1]; for (int i = 2; i < n ; ++i){ dp[i] = max(dp[i - 1], (i == 2 ? 0 : dp[i - 2]) + nums[i]); } int res2 = dp[n-1 ]; return max(res1, res2);//返回二者的较大值 } };