-
Notifications
You must be signed in to change notification settings - Fork 20.5k
Implement Maximum Sum of Non-Adjacent Elements #5544
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 18 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
ca64c74
feat: add Maximum Sum of Non-Adjacent Elements algorithm
Guhapriya01 0106b6f
feat: add URL for Maximum Sum of Non-Adjacent Elements algorithm refe…
Guhapriya01 7488ae3
Merge branch 'master' into master
Guhapriya01 81412e9
update code for checkstyle
Guhapriya01 8efc52e
Merge branch 'master' of https://github.com/Guhapriya01/Java
Guhapriya01 c7dcbea
format code
Guhapriya01 27699e3
format code using IDE formatter
Guhapriya01 04d499a
removed trailing spaces in comments
Guhapriya01 5c447f8
clang formatted
Guhapriya01 5e92f28
formatted using LLVM clang-formatter
Guhapriya01 dea0c18
formatted using LLVM clang-formatter
Guhapriya01 c6e3c63
added white space after and before curly braces
Guhapriya01 732708c
Merge branch 'master' into master
Guhapriya01 0fd5e20
Merge branch 'TheAlgorithms:master' into master
Guhapriya01 00618e1
Add unit test and format code in MaximumSumOfNonAdjacentElements and …
Guhapriya01 4b19e8f
Merge branch 'master' into master
Guhapriya01 d17c92d
Merge branch 'master' into master
Guhapriya01 11cd7ac
Merge branch 'master' into master
Guhapriya01 681e9e4
Merge branch 'TheAlgorithms:master' into master
Guhapriya01 5e07e78
refactor test structure for MaximumSumOfNonAdjacentElements
Guhapriya01 d64e300
format MaximumSumOfNonAdjacentElementsTest
Guhapriya01 8f4f67e
Merge branch 'master' into master
Guhapriya01 15b2f2b
refactor test method names in MaximumSumOfNonAdjacentElementsTest to …
Guhapriya01 533fae4
Merge branch 'master' of https://github.com/Guhapriya01/Java
Guhapriya01 2ceb130
Merge branch 'master' into master
siriak eeb2936
Merge branch 'master' into master
siriak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
95 changes: 95 additions & 0 deletions
95
src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
package com.thealgorithms.dynamicprogramming; | ||
|
||
/** | ||
* Class to find the maximum sum of non-adjacent elements in an array. This | ||
* class contains two approaches: one with O(n) space complexity and another | ||
* with O(1) space optimization. For more information, refer to | ||
* https://takeuforward.org/data-structure/maximum-sum-of-non-adjacent-elements-dp-5/ | ||
*/ | ||
final class MaximumSumOfNonAdjacentElements { | ||
|
||
private MaximumSumOfNonAdjacentElements() { | ||
} | ||
|
||
/** | ||
* Approach 1: Uses a dynamic programming array to store the maximum sum at | ||
* each index. Time Complexity: O(n) - where n is the length of the input | ||
* array. Space Complexity: O(n) - due to the additional dp array. | ||
* @param arr The input array of integers. | ||
* @return The maximum sum of non-adjacent elements. | ||
*/ | ||
public static int getMaxSumApproach1(int[] arr) { | ||
if (arr.length == 0) { | ||
return 0; // Check for empty array | ||
} | ||
|
||
int n = arr.length; | ||
int[] dp = new int[n]; | ||
|
||
// Base case: Maximum sum if only one element is present. | ||
dp[0] = arr[0]; | ||
|
||
for (int ind = 1; ind < n; ind++) { | ||
|
||
// Case 1: Do not take the current element, carry forward the previous max | ||
// sum. | ||
int notTake = dp[ind - 1]; | ||
|
||
// Case 2: Take the current element, add it to the max sum up to two | ||
// indices before. | ||
int take = arr[ind]; | ||
if (ind > 1) { | ||
take += dp[ind - 2]; | ||
} | ||
|
||
// Store the maximum of both choices in the dp array. | ||
dp[ind] = Math.max(take, notTake); | ||
} | ||
|
||
return dp[n - 1]; | ||
} | ||
|
||
/** | ||
* Approach 2: Optimized space complexity approach using two variables instead | ||
* of an array. Time Complexity: O(n) - where n is the length of the input | ||
* array. Space Complexity: O(1) - as it only uses constant space for two | ||
* variables. | ||
* @param arr The input array of integers. | ||
* @return The maximum sum of non-adjacent elements. | ||
*/ | ||
public static int getMaxSumApproach2(int[] arr) { | ||
if (arr.length == 0) { | ||
return 0; // Check for empty array | ||
} | ||
|
||
int n = arr.length; | ||
|
||
// Two variables to keep track of previous two results: | ||
// prev1 = max sum up to the last element (n-1) | ||
// prev2 = max sum up to the element before last (n-2) | ||
|
||
int prev1 = arr[0]; // Base case: Maximum sum for the first element. | ||
int prev2 = 0; | ||
|
||
for (int ind = 1; ind < n; ind++) { | ||
// Case 1: Do not take the current element, keep the last max sum. | ||
int notTake = prev1; | ||
|
||
// Case 2: Take the current element and add it to the result from two | ||
// steps back. | ||
int take = arr[ind]; | ||
if (ind > 1) { | ||
take += prev2; | ||
} | ||
|
||
// Calculate the current maximum sum and update previous values. | ||
int current = Math.max(take, notTake); | ||
|
||
// Shift prev1 and prev2 for the next iteration. | ||
prev2 = prev1; | ||
prev1 = current; | ||
} | ||
|
||
return prev1; | ||
} | ||
} |
30 changes: 30 additions & 0 deletions
30
src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package com.thealgorithms.dynamicprogramming; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
public class MaximumSumOfNonAdjacentElementsTest { | ||
|
||
@Test | ||
public void testGetMaxSumApproach1() { | ||
// Test with various cases | ||
assertEquals(15, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {3, 2, 5, 10, 7})); // 3 + 7 + 5 | ||
assertEquals(10, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {5, 1, 1, 5})); // 5 + 5 | ||
assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {})); // Empty array | ||
assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1})); // Single element | ||
assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1, 2})); // Take max of both | ||
assertEquals(3, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {3, 2})); // Take 3 | ||
} | ||
|
||
@Test | ||
public void testGetMaxSumApproach2() { | ||
// Test with various cases | ||
assertEquals(15, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {3, 2, 5, 10, 7})); // 3 + 7 + 5 | ||
assertEquals(10, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {5, 1, 1, 5})); // 5 + 5 | ||
assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {})); // Empty array | ||
assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1})); // Single element | ||
assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1, 2})); // Take max of both | ||
assertEquals(3, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {3, 2})); // Take 3 | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.