Skip to content

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 26 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from 21 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 Oct 3, 2024
0106b6f
feat: add URL for Maximum Sum of Non-Adjacent Elements algorithm refe…
Guhapriya01 Oct 3, 2024
7488ae3
Merge branch 'master' into master
Guhapriya01 Oct 3, 2024
81412e9
update code for checkstyle
Guhapriya01 Oct 3, 2024
8efc52e
Merge branch 'master' of https://github.com/Guhapriya01/Java
Guhapriya01 Oct 3, 2024
c7dcbea
format code
Guhapriya01 Oct 3, 2024
27699e3
format code using IDE formatter
Guhapriya01 Oct 3, 2024
04d499a
removed trailing spaces in comments
Guhapriya01 Oct 3, 2024
5c447f8
clang formatted
Guhapriya01 Oct 3, 2024
5e92f28
formatted using LLVM clang-formatter
Guhapriya01 Oct 3, 2024
dea0c18
formatted using LLVM clang-formatter
Guhapriya01 Oct 3, 2024
c6e3c63
added white space after and before curly braces
Guhapriya01 Oct 3, 2024
732708c
Merge branch 'master' into master
Guhapriya01 Oct 3, 2024
0fd5e20
Merge branch 'TheAlgorithms:master' into master
Guhapriya01 Oct 5, 2024
00618e1
Add unit test and format code in MaximumSumOfNonAdjacentElements and …
Guhapriya01 Oct 5, 2024
4b19e8f
Merge branch 'master' into master
Guhapriya01 Oct 5, 2024
d17c92d
Merge branch 'master' into master
Guhapriya01 Oct 6, 2024
11cd7ac
Merge branch 'master' into master
Guhapriya01 Oct 6, 2024
681e9e4
Merge branch 'TheAlgorithms:master' into master
Guhapriya01 Oct 8, 2024
5e07e78
refactor test structure for MaximumSumOfNonAdjacentElements
Guhapriya01 Oct 8, 2024
d64e300
format MaximumSumOfNonAdjacentElementsTest
Guhapriya01 Oct 8, 2024
8f4f67e
Merge branch 'master' into master
Guhapriya01 Oct 9, 2024
15b2f2b
refactor test method names in MaximumSumOfNonAdjacentElementsTest to …
Guhapriya01 Oct 9, 2024
533fae4
Merge branch 'master' of https://github.com/Guhapriya01/Java
Guhapriya01 Oct 9, 2024
2ceb130
Merge branch 'master' into master
siriak Oct 10, 2024
eeb2936
Merge branch 'master' into master
siriak Oct 10, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package com.thealgorithms.dynamicprogramming;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.Test;

public class MaximumSumOfNonAdjacentElementsTest {

// Tests for Approach1
@Test
public void testGetMaxSumApproach1_WithEmptyArray() {
assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {})); // Empty array
}

@Test
public void testGetMaxSumApproach1_WithSingleElement() {
assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1})); // Single element
}

@Test
public void testGetMaxSumApproach1_WithTwoElements_TakeMax() {
assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1, 2})); // Take max of both
}

@Test
public void testGetMaxSumApproach1_WithMultipleElements() {
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
}

// Tests for Approach2
@Test
public void testGetMaxSumApproach2_WithEmptyArray() {
assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {})); // Empty array
}

@Test
public void testGetMaxSumApproach2_WithSingleElement() {
assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1})); // Single element
}

@Test
public void testGetMaxSumApproach2_WithTwoElements_TakeMax() {
assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1, 2})); // Take max of both
}

@Test
public void testGetMaxSumApproach2_WithMultipleElements() {
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
}
}
Loading