[LeetCode .213] House Robber II
宣言:タイトルはLeetcodeから
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
Example 1:
Example 2:
Solution:
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
Example 1:
Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
because they are adjacent houses.
Example 2:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Solution:
class Solution {
public:
int rob(vector& nums) {
if(nums.size() == 0)
return 0;
if(nums.size() == 1)
return nums[0];
if(nums.size() == 2)
return max(nums[0], nums[1]);
if(nums.size() == 3)
return max( max(nums[0], nums[1]), nums[2]);
vector temp_1(nums.size() - 1);
vector temp_2(nums.size() - 1);
temp_1.assign(nums.begin(), nums.end() - 1);
temp_2.assign(nums.begin() + 1, nums.end());
int result_1 = find_max_money(temp_1);
int result_2 = find_max_money(temp_2);
return max(result_1, result_2);
}
private:
int find_max_money(vector &array)
{
vector max_money(array.size());
max_money[0] = array[0];
max_money[1] = array[1];
max_money[2] = max(array[0] + array[2], array[1]);
int result = max( max(max_money[0], max_money[1]), max_money[2] );
for(int i = 3; i < array.size(); i ++)
{
max_money[i] = array[i] + max(max_money[i - 2], max_money[i - 3]);
result = max(result, max_money[i]);
}
return result;
}
};