-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhouse-robber-ii.cpp
More file actions
37 lines (34 loc) · 849 Bytes
/
house-robber-ii.cpp
File metadata and controls
37 lines (34 loc) · 849 Bytes
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
class Solution {
public:
int rob(vector<int>& nums) {
int sz = nums.size();
int r = 0;
if (sz == 0) {return 0;}
if (sz < 4) {
for (int i=0;i<sz;i++){
r = max(r, nums[i]);
}
return r;
}
// From 0 to n-1
vector<int> res(sz,0);
res[0] = nums[0];
res[1] = max(nums[1],nums[0]);
int i=2;
while (i < sz-1){
res[i] = max(res[i-1], res[i-2] + nums[i]);
i++;
}
r = res[sz-2];
// From 1 to n
res.clear();
res[1] = nums[1];
res[2] = max(nums[1],nums[2]);
i = 3;
while (i<sz){
res[i] = max(res[i-1], res[i-2] + nums[i]);
i++;
}
return max(r, res[sz-1]);
}
};