Skip to content

Commit 5c7a056

Browse files
authored
Merge pull request #125 from Adityakumar37/add-max
Added solution for Maximum Sum of Non-Adjacent Elements problem
2 parents d798ce3 + 76bf090 commit 5c7a056

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// Function to find the maximum sum of non-adjacent elements
5+
int maxNonAdjacentSum(vector<int>& nums) {
6+
int n = nums.size();
7+
8+
// Edge cases
9+
if (n == 0) return 0;
10+
if (n == 1) return nums[0];
11+
12+
// incl = max sum including current element
13+
// excl = max sum excluding current element
14+
int incl = nums[0];
15+
int excl = 0;
16+
17+
for (int i = 1; i < n; i++) {
18+
int new_excl = max(incl, excl); // maximum till previous element
19+
incl = excl + nums[i]; // include current element
20+
excl = new_excl; // update exclude
21+
}
22+
23+
// Final answer is the max of incl and excl
24+
return max(incl, excl);
25+
}
26+
27+
int main() {
28+
vector<int> nums1 = {3, 2, 7, 10};
29+
vector<int> nums2 = {3, 2, 5, 10, 7};
30+
31+
cout << "Example 1 Output: " << maxNonAdjacentSum(nums1) << endl; // 13
32+
cout << "Example 2 Output: " << maxNonAdjacentSum(nums2) << endl; // 15
33+
34+
return 0;
35+
}

0 commit comments

Comments
 (0)