Skip to content

Commit 55199ea

Browse files
authored
Update MaximumSumOfNonAdjacentElements.java
Added handling for single-element arrays. Made the take calculation more concise. Kept the variable update logic the same but provided better explanations. Improved comment clarity and consistency.
1 parent 169a01e commit 55199ea

File tree

1 file changed

+20
-21
lines changed

1 file changed

+20
-21
lines changed

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

Lines changed: 20 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -58,36 +58,35 @@ public static int getMaxSumApproach1(int[] arr) {
5858
* @return The maximum sum of non-adjacent elements.
5959
*/
6060
public static int getMaxSumApproach2(int[] arr) {
61+
// Check for an empty array, return 0 as no elements to sum
6162
if (arr.length == 0) {
62-
return 0; // Check for empty array
63+
return 0;
64+
}
65+
// If there's only one element, return that element as the result
66+
if (arr.length == 1) {
67+
return arr[0];
6368
}
6469

65-
int n = arr.length;
66-
67-
// Two variables to keep track of previous two results:
68-
// prev1 = max sum up to the last element (n-1)
69-
// prev2 = max sum up to the element before last (n-2)
70+
// Initialize two variables to store the maximum sums:
71+
int prev1 = arr[0]; // Maximum sum up to the first element.
72+
int prev2 = 0; // Base case for the element before the first.
7073

71-
int prev1 = arr[0]; // Base case: Maximum sum for the first element.
72-
int prev2 = 0;
74+
// Iterate over the array starting from the second element.
75+
for (int ind = 1; ind < arr.length; ind++) {
76+
// Calculate the sum if taking the current element:
77+
// Include arr[ind] + prev2 (if index > 1)
78+
int take = arr[ind] + (ind > 1 ? prev2 : 0);
7379

74-
for (int ind = 1; ind < n; ind++) {
75-
// Case 1: Do not take the current element, keep the last max sum.
80+
// Calculate the sum if not taking the current element:
81+
// Take the sum as it is up to the previous element.
7682
int notTake = prev1;
7783

78-
// Case 2: Take the current element and add it to the result from two
79-
// steps back.
80-
int take = arr[ind];
81-
if (ind > 1) {
82-
take += prev2;
83-
}
84-
85-
// Calculate the current maximum sum and update previous values.
84+
// Determine the maximum of taking or not taking the current element.
8685
int current = Math.max(take, notTake);
8786

88-
// Shift prev1 and prev2 for the next iteration.
89-
prev2 = prev1;
90-
prev1 = current;
87+
// Update the values for the next iteration:
88+
prev2 = prev1; // Shift prev2 to the last element's sum.
89+
prev1 = current; // Update prev1 with the current maximum sum.
9190
}
9291

9392
return prev1;

0 commit comments

Comments
 (0)