-
Notifications
You must be signed in to change notification settings - Fork 110
/
198-house-robber.cpp
43 lines (41 loc) · 1.02 KB
/
198-house-robber.cpp
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
40
41
42
43
// Time: O(N), Space: O(1)
class Solution {
public:
int rob(vector<int>& nums) {
int len = nums.size();
if (len == 0) {
return 0;
}
if (len == 1) {
return nums[0];
}
int prevPrev = nums[0];
int prev = max(nums[0], nums[1]);
for (int i = 2; i < len; i++) {
int curr = max(prev, nums[i] + prevPrev);
prevPrev = prev;
prev = curr;
}
return prev;
}
};
// Time: O(N), Space: O(N)
class Solution {
public:
int rob(vector<int>& nums) {
int len = nums.size();
if (len == 0) {
return 0;
}
if (len == 1) {
return nums[0];
}
vector<int> profit(len, 0);
profit[0] = nums[0];
profit[1] = max(nums[0], nums[1]);
for (int i = 2; i < len; i++) {
profit[i] = max(profit[i - 1], nums[i] + profit[i - 2]);
}
return profit[len - 1];
}
};