Repository: TheAlgorithms/Java
Pull request #5544 (2024-10-03 10:55:07)

 Implement Maximum Sum of Non-Adjacent Elements
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

This PR adds an algorithm to find the maximum sum of non-adjacent elements in an array. The implementation includes two approaches:

**Dynamic Programming with O(n) Space Complexity:**

- Utilizes a dynamic programming array to store the maximum sum at each index.
- Time Complexity: O(n)
- Space Complexity: O(n)

**Optimized Space Complexity Approach:**

- Uses two variables to track the maximum sums, reducing space complexity to O(1).
- Time Complexity: O(n)
- Space Complexity: O(1)

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

**Related Issues :** Issue #5510 

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5544?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `0%` with `22 lines` in your changes missing coverage. Please review.
> Project coverage is 52.85%. Comparing base [(`7b934af`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/7b934af257208f0dc1a06ba5d2e74ee808f78387?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`0106b6f`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/0106b6f828e5aff44d56c491c98c073f3d9da373?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).
> Report is 1 commits behind head on master.

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5544?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...icprogramming/MaximumSumOfNonAdjacentElements.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5544?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fdynamicprogramming%2FMaximumSumOfNonAdjacentElements.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9keW5hbWljcHJvZ3JhbW1pbmcvTWF4aW11bVN1bU9mTm9uQWRqYWNlbnRFbGVtZW50cy5qYXZh) | 0.00% | [22 Missing :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5544?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5544      +/-   ##
============================================
+ Coverage     52.84%   52.85%   +0.01%     
  Complexity     3306     3306              
============================================
  Files           529      529              
  Lines         15361    15352       -9     
  Branches       2926     2926              
============================================
- Hits           8117     8115       -2     
+ Misses         6911     6903       -8     
- Partials        333      334       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5544?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

Guhapriya01: Hi @siriak , I've addressed your feedback by fixing the Clang PR check and adding JUnit tests for the `MaximumSumOfNonAdjacentElements` class.

Patch:
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java b/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java
new file mode 100644
index 00000000..49af3ae3
--- /dev/null
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java
@@ -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;
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java b/src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java
new file mode 100644
index 00000000..3f312d86
--- /dev/null
+++ b/src/test/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElementsTest.java
@@ -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 testGetMaxSumApproach1WithEmptyArray() {
+        assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {})); // Empty array
+    }
+
+    @Test
+    public void testGetMaxSumApproach1WithSingleElement() {
+        assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1})); // Single element
+    }
+
+    @Test
+    public void testGetMaxSumApproach1WithTwoElementsTakeMax() {
+        assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach1(new int[] {1, 2})); // Take max of both
+    }
+
+    @Test
+    public void testGetMaxSumApproach1WithMultipleElements() {
+        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 testGetMaxSumApproach2WithEmptyArray() {
+        assertEquals(0, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {})); // Empty array
+    }
+
+    @Test
+    public void testGetMaxSumApproach2WithSingleElement() {
+        assertEquals(1, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1})); // Single element
+    }
+
+    @Test
+    public void testGetMaxSumApproach2WithTwoElementsTakeMax() {
+        assertEquals(2, MaximumSumOfNonAdjacentElements.getMaxSumApproach2(new int[] {1, 2})); // Take max of both
+    }
+
+    @Test
+    public void testGetMaxSumApproach2WithMultipleElements() {
+        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
+    }
+}