-
Notifications
You must be signed in to change notification settings - Fork 66
/
Maximum sum of non-adjacent elements
129 lines (74 loc) · 1.83 KB
/
Maximum sum of non-adjacent elements
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
//I am going to solve this question by 4 method
class Solution {
public:
// 1st Method RECURSIVE SOLUTION
int solve(vector<int>&nums, int n){
//base condition
if(n<0)
return 0;
if(n==0)
return nums[0];
int incl=solve(nums,n-2)+nums[n];
int excl= solve(nums,n-1) +0;
return max(incl, excl);
}
int maximumNonAdjacentSum(vector<int>&nums) {
int n=nums.size();
int ans= solve(nums,n-1);
return ans;
}
};
//2nd Method: RECURSION+ MEMOIZATION
int solveMem(vector<int>&nums,int n, vector<int>&dp){
//base condition
if(n<0)
return 0;
if(n==0)
return nums[0];
if(dp[n]!=-1)
return dp[n];
int incl=solveMem(nums,n-2)+nums[n];
int excl= solveMem(nums,n-1) +0;
dp[n]=max(incl,excl);
return dp[n];
}
int maximumNonAdjacentSum(vector<int>&nums){
int n=nums.size();
vector<int>dp(n,-1);
return solveMem(nums,n-1,dp);
}
//3rd Method: TABULATION
int solveTab(vector<int>&nums){
int n=nums.size();
vector<int>dp(n,0);
dp[0]=nums[0];
for(int i=1; i<n; i++){
int incl=dp[i-2]+nums[i];
int excl= dp[i-1]+ 0;
dp[i]= max(incl,excl);
}
return dp[n-1];
}
int maximumNonAdjacentSum(vector<int>&nums){
int n=nums.size();
return solveTab(nums);
}
//4th Method: Space Opimisation
int solveSo(vector<int>&nums){
int n=nums.size();
int prev2=0;
int prev1=nums[0];
for(int i=1; i<n; i++){
int incl=prev2+nums[i];
int excl=prev1+0;
int ans=max(incl,excl);
prev2=prev1;
prev1=ans;
}
return prev1;
}
int maximumNonAdjacentSum(vector<int>&nums){
int n=nums.size();
return solveSo(nums);
}
//THANKS FOR READING HOPE YOU ENJOY IT