713543. Max Sum without Adjacents
Max Sum without Adjacents
Summary
Given an array of integers, find the maximum sum that can be obtained by selecting elements in such a way that no adjacent elements are selected. This problem is related to dynamic programming and arrays.
Detailed Explanation
The approach to solve this problem is to use dynamic programming. We create an array dp where dp[i] represents the maximum sum that can be obtained up to the i-th element without selecting any of its adjacent elements. The base case for our recurrence relation is when we have only one element left, in which case the maximum sum is just the value of that element.
We then iterate through the array from left to right, considering each element as a potential starting point for our subarray. For each such subarray, we calculate the maximum sum that can be obtained by including or excluding its last element. We exclude the last element if it was included in the previous subarray and include it otherwise.
Here is the step-by-step breakdown of the solution:
- Initialize
dp[0]to the value of the first element. - For each
ifrom 1 ton-1, wherenis the length of the array:- If we don't select the current element, our maximum sum remains the same as in the previous step (
dp[i-1]). - If we do select the current element, our maximum sum is the value of the current element plus the maximum sum that can be obtained without selecting its adjacent elements (
dp[i-2]ifiis even, ordp[i-3]ifiis odd).
- If we don't select the current element, our maximum sum remains the same as in the previous step (
- The maximum sum that can be obtained is stored in
dp[n-1].
The time complexity of this algorithm is O(n), where n is the length of the array. This is because we make a single pass through the array.
The space complexity is also O(n) for storing the dp array.
Optimized Solutions
Java
public int maxSumWithoutAdjacents(int[] arr) {
if (arr.length == 1) return arr[0];
int[] dp = new int[arr.length];
dp[0] = arr[0];
dp[1] = Math.max(arr[0], arr[1]);
for (int i = 2; i < arr.length; i++) {
dp[i] = Math.max(dp[i-1], dp[i-2] + arr[i]);
}
return dp[arr.length - 1];
}