-
Notifications
You must be signed in to change notification settings - Fork 0
/
HouseRobber-I.cpp
124 lines (89 loc) · 2.54 KB
/
HouseRobber-I.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include<bits/stdc++.h>
using namespace std;
// * Recursive Approach
// * T.C : O(2^n)
int helper(int idx, vector<int>& nums, int sum) {
if(idx >= nums.size())
return sum;
int pick = helper(idx+2, nums, sum + nums[idx]);
int notPick = helper(idx+1, nums, sum);
return max(pick, notPick);
}
// * Memoization Approach :
// * T.C : O(N), S.C :O(N)
int helper(int idx, vector<int>& nums, vector<int> &dp) {
if(idx >= nums.size()) return 0;
if(dp[idx] != -1) return dp[idx];
int pick = helper(idx+2, nums, dp) + nums[idx];
int notPick = helper(idx+1, nums, dp);
return dp[idx] = max(pick, notPick);
}
// * Tabulation - BOTTOM UP Approach
// * T.C : O(N), S.C :O(N)
int rob(vector<int>& nums) {
vector<int> dp(nums.size(), -1);
dp[0] = nums[0];
int neg = 0;
for(int i = 1; i < nums.size(); i++) {
int take = nums[i];
if(i > 1)
take += dp[i-2];
int notTake = dp[i-1];
dp[i] = max(take, notTake);
}
return dp[nums.size() - 1];
}
// * Tabulation with Space Optimised
// * T.C : O(N), S.C :O(1)
int rob(vector<int>& nums) {
int prevIdx = nums[0], prev2Idx = 0, currIdx = 0;
for(int i = 1; i < nums.size(); i++) {
int take = nums[i] + prev2Idx;
int notTake = prevIdx;
currIdx = max(take, notTake);
prev2Idx = prevIdx;
prevIdx = currIdx;
}
return prevIdx;
}
// * PRACTICE - 1
// * Recursive Approach
// * T.C : O(2^n)
int helper(int idx, vector<int>& nums, int sum) {
if(idx >= nums.size())
return sum;
int pick = helper(idx+2, nums, sum + nums[idx]);
int notPick = helper(idx+1, nums, sum);
return max(pick, notPick);
}
int helper(int idx, vector<int>& nums, vector<int> &dp) {
if(idx >= nums.size()) return 0;
if(dp[idx] != -1) return dp[idx];
int pick = helper(idx+2, nums, dp) + nums[idx];
int notPick = helper(idx+1, nums, dp);
return dp[idx] = max(pick, notPick);
}
int rob(vector<int>& nums) {
vector<int> dp(nums.size(), -1);
dp[0] = nums[0];
int neg = 0;
for(int i = 1; i < nums.size(); i++) {
int take = nums[i];
if(i > 1)
take += dp[i-2];
int notTake = dp[i-1];
dp[i] = max(take, notTake);
}
return dp[nums.size() - 1];
}
int rob(vector<int>& nums) {
int prevIdx = nums[0], prev2Idx = 0, currIdx = 0;
for(int i = 1; i < nums.size(); i++) {
int take = nums[i] + prev2Idx;
int notTake = prevIdx;
currIdx = max(take, notTake);
prev2Idx = prevIdx;
prevIdx = currIdx;
}
return prevIdx;
}