[LeetCode] House Robber II
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 arearranged 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.
https://leetcode.com/problems/house-robber-ii/
LeetCode这是一天一道题的节奏吗?这道题就是在上一题的基础上加了一个条件,变成了环,所以如果抢了第一家,就不能抢最后一家。所以我们可以分别计算抢了从第二家到最后一家与抢从第一家到倒数第二家的最大值,取两个值中更大的那个就是结果。
1 class Solution { 2 public: 3 int rob(vector<int> &num) { 4 if (num.size() == 0) return 0; 5 if (num.size() == 1) return num[0]; 6 vector<int> dp(num.size()); 7 //抢第一家到倒数第二家的最大值 8 dp[0] = num[0]; 9 for (int i = 1; i < num.size() - 1; ++i) 10 dp[i] = max(dp[i-1], (i == 1 ? 0 : dp[i-2]) + num[i]); 11 int res = dp[num.size()-2]; 12 //抢第二家到最后一家的最大值 13 dp[1] = num[1]; 14 for (int i = 2; i < num.size() ; ++i) 15 dp[i] = max(dp[i-1], (i == 2 ? 0 : dp[i-2]) + num[i]); 16 //返回两者较大的一个 17 return max(res, dp[num.size()-1]); 18 } 19 };