forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhouse-robber.cpp
More file actions
27 lines (25 loc) · 752 Bytes
/
house-robber.cpp
File metadata and controls
27 lines (25 loc) · 752 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
//Solution 1: dp solution
// time: O(n)
// space: O(1)
// 3ms
class Solution {
public:
int rob(vector<int> &num) {
//dp[i][0] => max money from 0~i house with the ith house not robbed
//dp[i][1] => max money from 0~i house with the ith house robbed
//dp[i][0] = max(dp[i-1][0], dp[i-1][1]);
//dp[i][1] = dp[i-1][0] + num[i];
//dp space can be compressed
if (num.empty()) {
return 0;
}
int dp[2] = {0, num[0]};
int tmp = 0;
for (int i = 1; i < num.size(); ++i) {
tmp = dp[0];
dp[0] = max(dp[0], dp[1]);
dp[1] = tmp + num[i];
}
return max(dp[0], dp[1]);
}
};