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.
https://www.youtube.com/watch?v=-i2BFAU25Zk
方法1:
思路: 需要maintain 4 个变量(对比198中maintain 2 个dp值),相当于两组198。
第一组记录condition on rob first 的dp
r_rf: rob current, robbed first
nr_rf: not rob current, robbed first
第二组记录condition on not rob first 的dp
r_nrf: rob current, not robbed first
nr_nrf: not rob current, not rob first
不化简:
code
易错点:
- c++初始化不是0,是signed INT_MIN,会造成结果有差异!
- 注意new array在c++中的语法
int [] a= new int[n]; 是错误的 - two_rf 对应?王的rob_rf 是一个虽然最终不合法但是需要update并作为初始化起点的值
- 为什么不把one_rf 初始化成nums[0] ?
int rob(vector<int>& nums) {
if (nums.size() == 0) return 0;
if (nums.size() == 1) return nums[0];
int n = nums.size();
// c++初始化不是0,是signed INT_MIN
// 会造成结果有差异!
int* two_rf = new int[n];
int* one_rf = new int[n];
int* two_nrf = new int[n];
int* one_nrf = new int[n];
two_rf[0] = nums[0];
one_rf[0] = 0;
two_nrf[0] = 0;
one_nrf[0] = 0;
for (int i = 1; i < nums.size(); i++){
two_rf[i] = one_rf[i - 1] + nums[i];
one_rf[i] = max(two_rf[i - 1], one_rf[i - 1]);
two_nrf[i] = one_nrf[i - 1] + nums[i];
one_nrf[i] = max(two_nrf[i - 1], one_nrf[i - 1]);
}
return max(one_rf[n - 1], two_nrf[n -1] );
}
};
化简:
code
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() == 0) return 0;
if (nums.size() == 1) return nums[0];
int one_rf = 0;
int two_rf = nums[0];
int one_nrf = 0;
int two_nrf = 0;
for (int i = 1; i < nums.size(); i++){
int dp_rf = one_rf + nums[i];
one_rf = max(two_rf, one_rf);
two_rf = dp_rf;
int dp_nrf = one_nrf + nums[i];
one_nrf = max(two_nrf, one_nrf);
two_nrf = dp_nrf;
}
return max(one_rf, max(two_nrf, one_nrf)) ;
}
};