Skip to content

Commit d47cc86

Browse files
Merge pull request #595 from thisabhijeet/maximumNonAdjacentSum
maximumNonAdjacentSum.cpp created
2 parents 16230cd + f10e37f commit d47cc86

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// Problem : Given an array of ‘N’ positive integers, we need to return the maximum sum of the subsequence such that no two elements of the subsequence are adjacent elements in the array.
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
// Recursive Approach starts
7+
8+
int maximumNonAdjacentSum(int ind, vector<int> &arr, vector<int> &dp)
9+
{
10+
if (ind == 0)
11+
{
12+
return arr[0];
13+
}
14+
else if (ind == 1)
15+
{
16+
return max(arr[0], arr[1]);
17+
}
18+
if (dp[ind] != -1)
19+
{
20+
return dp[ind];
21+
}
22+
// there can be two cases for an element, either we keep it, so we discard the element adjacent to it, or else we discard the current element so that we can move ahead and make decision for the adjacent element and then return the maximum of both of these choices
23+
int pick = arr[ind] + maximumNonAdjacentSum(ind - 2, arr, dp);
24+
int nonPick = maximumNonAdjacentSum(ind - 1, arr, dp);
25+
return dp[ind] = max(pick, nonPick);
26+
}
27+
28+
int solve(int n, vector<int> &arr)
29+
{
30+
vector<int> dp(n, -1);
31+
return maximumNonAdjacentSum(n - 1, arr, dp);
32+
}
33+
34+
// Recursive Approach ends
35+
36+
// Tabulation Approach starts
37+
38+
// int maximumNonAdjacentSum(vector<int> &nums)
39+
// {
40+
// int n = nums.size();
41+
// if (n == 1)
42+
// {
43+
// return nums[0];
44+
// }
45+
// vector<int> v(n, 0);
46+
// v[0] = nums[0];
47+
// v[1] = max(nums[0], nums[1]);
48+
// for (int i = 2; i < n; i++)
49+
// {
50+
// v[i] = max(nums[i] + v[i - 2], v[i - 1]);
51+
// }
52+
// return v[n - 1];
53+
// }
54+
55+
// Tabulation approach ends
56+
57+
int main()
58+
{
59+
int n;
60+
cin >> n;
61+
vector<int> arr(n);
62+
for (int i = 0; i < n; i++)
63+
{
64+
cin >> arr[i];
65+
}
66+
cout << solve(n, arr);
67+
}
68+
69+
// Sample Inputs
70+
71+
// 4 2 1 4 9
72+
// 3 1 2 4
73+
// 9 1 2 3 1 3 5 8 1 9
74+
75+
// Corresponding Outputs
76+
77+
// 11
78+
// 5
79+
// 24

0 commit comments

Comments
 (0)