213. House Robber II
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.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.// Dynamic Programming
int rob(vector<int>& nums) { // time: O(n); space: O(n)
if (nums.empty()) return 0;
int n = nums.size();
if (n == 1) return nums[0];
// money1: Rob the first and not rob the last
// money2: Not rob the first and rob the last
vector<int> money1(n, 0), money2(n, 0);
for (int i = 0; i < n; ++i) {
if (i != n - 1)
money1[i] = max((i > 0 ? money1[i - 1] : 0), (i > 1 ? money1[i - 2] : 0) + nums[i]);
if (i != 0)
money2[i] = max((i > 0 ? money2[i - 1] : 0), (i > 1 ? money2[i - 2] : 0) + nums[i]);
}
return max(money1[n - 2], money2[n - 1]);
}Last updated