710036. Max Sum without Adjacents 2
Medium
Max Sum without Adjacents 2
Slug: max-sum-without-adjacents-2
Difficulty: Medium
Topic Tags: Dynamic Programming, Greedy, Arrays
Company Tags: None
Summary
The problem "Max Sum without Adjacents 2" is a dynamic programming problem that involves finding the maximum sum of non-adjacent elements in an array. The key concept involved is based on dynamic programming and greedy algorithms.
Detailed Explanation
Let's break down the solution step by step:
- Initialize the maximum sum
max_sumto the first element of the array. - Iterate through the array, considering each element from the second one (since we can't include the first element).
- For each element, calculate the maximum sum that includes this element and the previous non-adjacent element.
- Update the
max_sumif the calculated sum is greater than the currentmax_sum. - Return the maximum sum found.
Here's a step-by-step breakdown of the solution:
1 2 3 4 5
max_sum = 2
|
|--- 3 (max_sum + 3)
|--- 5 (max_sum + 5)
|--- 4 (max_sum + 4)
|--- 2 (max_sum + 2)
Time complexity: O(n), where n is the length of the array. Space complexity: O(1).
Optimized Solutions
Java
public int maxSumWithoutAdjacents(int[] arr) {
if(arr.length == 0) return 0;
if(arr.length == 1) return arr[0];
int max_sum = arr[0];
for(int i = 1; i < arr.length - 1; i++) {
max_sum = Math.max(max_sum, arr[i] + (i > 0 ? arr[i-2] : 0));
}
return max_sum;
}