Skip to content

Commit 88b79b5

Browse files
committed
Add Maximum Sum of Non-Adjacent Elements Algorithm
1 parent 456ae51 commit 88b79b5

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/main/java/com/thealgorithms/dynamicprogramming/MaxSumNonAdjacent.java

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@
22

33
import java.util.*;
44

5+
/*
6+
What would you like to Propose?
7+
I would like to propose adding an implementation of the Maximum Sum of Non-Adjacent Elements
8+
algorithm to the dynamic programming section of the repository. Issue details Problem Statement:
9+
Given an array of integers, write a function to find the maximum sum of non-adjacent elements. The
10+
elements can be chosen such that no two chosen elements are adjacent in the array. For example:
11+
Input: [3, 2, 5, 10, 7]
12+
Output: 15 (The maximum sum is obtained by selecting 3, 7, and 5)
13+
Approach:
14+
Use dynamic programming to maintain a running maximum sum.
15+
For each element, decide to either include it in the sum (and skip the previous element) or exclude
16+
it (and keep the sum up to the previous element).*/
517
// Problem explanation:
618
// "https://medium.com/@amitrajit_bose/max-sum-of-non-adjacent-elements-a04ebc4f2602"
719

@@ -57,10 +69,10 @@ public static void main(String[] args) {
5769
for (int i = 0; i < n; i++) { nums[i] = sc.nextInt(); }
5870

5971
// Call the solve function to find the maximum possible sum.
60-
int result = solve(n, nums);
72+
int ans = solve(n, nums);
6173

6274
// Print the result.
63-
System.out.println("Maximum sum of non-adjacent elements: " + result);
75+
System.out.println("Maximum sum of non-adjacent elements: " + ans);
6476

6577
sc.close(); // Close the scanner to prevent resource leakage.
6678
}

0 commit comments

Comments
 (0)