@@ -58,36 +58,35 @@ public static int getMaxSumApproach1(int[] arr) {
58
58
* @return The maximum sum of non-adjacent elements.
59
59
*/
60
60
public static int getMaxSumApproach2 (int [] arr ) {
61
+ // Check for an empty array, return 0 as no elements to sum
61
62
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 ];
63
68
}
64
69
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.
70
73
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 );
73
79
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 .
76
82
int notTake = prev1 ;
77
83
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.
86
85
int current = Math .max (take , notTake );
87
86
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.
91
90
}
92
91
93
92
return prev1 ;
0 commit comments