Skip to content

Commit bad84a1

Browse files
committed
Add Maximum Sum of Non-Adjacent Elements DP solution
1 parent 0bd86b3 commit bad84a1

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
public final class MaximumSumOfNonAdjacanetElement {
4+
5+
private MaximumSumOfNonAdjacanetElement() {
6+
7+
}
8+
9+
public static int maxSumNonAdjacent(int[] nums) {
10+
if (nums == null || nums.length == 0)
11+
return 0;
12+
if (nums.length == 1)
13+
return nums[0];
14+
15+
int[] dp = new int[nums.length];
16+
17+
dp[0] = nums[0];
18+
dp[1] = Math.max(nums[0], nums[1]);
19+
20+
for (int i = 2; i < nums.length; i++) {
21+
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
22+
}
23+
24+
return dp[nums.length - 1];
25+
}
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import org.junit.jupiter.api.Test;
5+
6+
class MaxSumNonAdjacentTest {
7+
@Test
8+
public void testMaxSumNonAdjacentWithMultipleElements() {
9+
int[] array = { 3, 2, 5, 10, 7 };
10+
assertEquals(15, MaximumSumOfNonAdjacanetElement.maxSumNonAdjacent(array));
11+
}
12+
13+
@Test
14+
public void testMaxSumNonAdjacentWithAllPositiveNumbers() {
15+
int[] array = { 5, 5, 10, 100, 10, 5 };
16+
assertEquals(110, MaximumSumOfNonAdjacanetElement.maxSumNonAdjacent(array));
17+
}
18+
19+
@Test
20+
public void testMaxSumNonAdjacentWithSingleElement() {
21+
int[] array = { 7 };
22+
assertEquals(7, MaximumSumOfNonAdjacanetElement.maxSumNonAdjacent(array));
23+
}
24+
25+
@Test
26+
public void testMaxSumNonAdjacentWithEmptyArray() {
27+
int[] array = {};
28+
assertEquals(0, MaximumSumOfNonAdjacanetElement.maxSumNonAdjacent(array));
29+
}
30+
31+
@Test
32+
public void testMaxSumNonAdjacentWithNegativeNumbers() {
33+
int[] array = { 5, -2, 10, -4, 6 };
34+
assertEquals(16, MaximumSumOfNonAdjacanetElement.maxSumNonAdjacent(array));
35+
}
36+
37+
@Test
38+
public void testMaxSumNonAdjacentWithAllNegativeNumbers() {
39+
int[] array = { -1, -2, -3, -4 };
40+
assertEquals(0, MaximumSumOfNonAdjacanetElement.maxSumNonAdjacent(array));
41+
}
42+
43+
@Test
44+
public void testMaxSumNonAdjacentWithLargeNumbers() {
45+
int[] array = { 1000, 2000, 3000, 4000, 5000 };
46+
assertEquals(9000, MaximumSumOfNonAdjacanetElement.maxSumNonAdjacent(array));
47+
}
48+
}

0 commit comments

Comments
 (0)