forked from abhishekSharmaGithub/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHouse Robber
More file actions
43 lines (33 loc) · 926 Bytes
/
Copy pathHouse Robber
File metadata and controls
43 lines (33 loc) · 926 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
38
39
40
41
42
43
class Solution {
private:
int solve(int index, vector<int>&dp,vector<int>& nums){
if(index==0){
return nums[index];
}
if(index<0){
return 0;
}
int nottake=0+solve(index-1,dp,nums);
int take =nums[index]+solve(index-2,dp,nums);
dp[index]=max(take,nottake);
return dp[index];
}
public:
int rob(vector<int>& nums) {
int n=nums.size();
// vector<int>dp(n,-1);
// return solve(n-1,dp,nums);
vector<int>dp(n,0);
dp[0]=nums[0];
int neg=0;
int i;
for(i=1;i<n;i++){
int take=nums[i];
if(i>1){
take+=dp[i-2];}
int nottake=0+dp[i-1];
dp[i]=max(take,nottake);
}
return dp[n-1];
}
};