-
Notifications
You must be signed in to change notification settings - Fork 0
/
House Robber II
39 lines (34 loc) · 1.35 KB
/
House Robber II
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
LeetCode 213:
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.
Solution:
Language: C++
Tag: DP
*/
class Solution {
public:
#define max(a, b) (a > b ? a : b)
int rob(vector<int>& nums) {
if (nums.empty()) {
return 0;
}
if (nums.size() == 1) {
return nums[0];
}
// 1. DP: O(n) time + O(1) space
int with0 = houseRobber(nums, 0, nums.size() - 1);
int with1 = houseRobber(nums, 1, nums.size() - 1);
return max(with0, with1);
}
int houseRobber(vector<int> &nums, int start, int size) {
int *f = new int[3];
f[0] = 0;
f[1] = nums[start];
for (int i = 2; i <= size; ++i) {
f[i % 3] = max(f[(i - 1) % 3], f[(i - 2) % 3] + nums[i + start - 1]);
}
return f[size % 3];
}
};