-
Notifications
You must be signed in to change notification settings - Fork 1
/
198. House Robber.cpp
75 lines (67 loc) · 2.13 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/************* Method - 1 (Top-Down Approach; TC - O(N); SC - O(N)) **********
class Solution {
public:
// <data-type of ans> f(<Subproblem representation>, <Dp table>)
int robHelper(vector<int>& nums, int start, vector<int>& dp) {
int n = nums.size();
// Base case
if(start == n-1)
return nums[n-1];
if(start == n)
return 0;
// Checking if already computed
if(dp[start] != -1)
return dp[start];
// Recursive Calls
dp[start] = max(nums[start] + robHelper(nums, start+2, dp), robHelper(nums, start+1, dp));
return dp[start];
}
int rob(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n, -1);
return robHelper(nums, 0, dp);
}
};
*************************************************************/
/************* Method - 2 (Bottom-Up Approach; TC - O(N); SC - O(N)) **********
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n+1);
dp[n] = 0;
dp[n-1] = nums[n-1];
for(int i = n-2; i >= 0; i--)
dp[i] = max(nums[i] + dp[i+2], dp[i+1]);
return dp[0];
}
};
*************************************************************/
/************* Method - 3 (Bottom-Up Approach; TC - O(N); SC - O(1)) **********
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
// vector<int> dp(n+1);
int a = 0, b = nums[n-1], c = nums[n-1];
for(int i = n-2; i >= 0; i--) {
c = max(nums[i] + a, b);
a = b;
b = c;
}
return c;
}
};
*********************************************************************************/
/************* Method - 4 {Shortest Code} (Bottom-Up Approach; TC - O(N); SC - O(1)) **********/
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
vector<int> dp(2, 0);
dp[(n-1)%2] = nums[n-1];
for(int i = n-2; i >= 0; i--)
dp[i%2] = max(nums[i] + dp[i%2], dp[(i+1)%2]);
return dp[0];
}
};