-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.3)MaxSumof_Non-Adjacent
More file actions
97 lines (81 loc) · 1.71 KB
/
Copy path1.3)MaxSumof_Non-Adjacent
File metadata and controls
97 lines (81 loc) · 1.71 KB
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
Maximum sum of non-adjacent elements - https://www.codingninjas.com/codestudio/problems/maximum-sum-of-non-adjacent-elements_843261
1) Recursion :
Gives TLE
#include<bits/stdc++.h>
int rec(int n, vector<int>& nums)
{
if(n==0)
{
return nums[0];
}
if(n<0)
{
return 0;
}
int take = nums[n] + rec(n-2,nums);
int notTake = 0 + rec(n-1,nums);
return max(take,notTake);
}
int maximumNonAdjacentSum(vector<int> &nums){
int n=nums.size();
return rec(n-1,nums);
}
2) Memoization :
#include<bits/stdc++.h>
int rec(int n, vector<int>& nums, vector<int>& dp)
{
if(n==0)
{
return nums[0];
}
if(n<0)
{
return 0;
}
if(dp[n]!=-1)
{
return dp[n];
}
int take = nums[n] + rec(n-2,nums,dp);
int notTake = 0 + rec(n-1,nums,dp);
return dp[n] = max(take,notTake);
}
int maximumNonAdjacentSum(vector<int> &nums){
int n=nums.size();
vector<int> dp(n+1,-1);
return rec(n-1,nums,dp);
}
3) Tabulation :
int maximumNonAdjacentSum(vector<int> &nums){
int n=nums.size();
vector<int> dp(n,0);
dp[0]=nums[0];
for(int 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];
}
4) Space Optimization :
int maximumNonAdjacentSum(vector<int> &nums){
int prev=nums[0],prev1=0;
for(int i=0;i<nums.size();i++)
{
int take = nums[i];
if(i>1)
{
take+=prev1;
}
int notTake = prev;
int curr=max(take,notTake);
prev1=prev;
prev=curr;
}
return prev;
}