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:

  1. Initialize the maximum sum max_sum to the first element of the array.
  2. Iterate through the array, considering each element from the second one (since we can't include the first element).
  3. For each element, calculate the maximum sum that includes this element and the previous non-adjacent element.
  4. Update the max_sum if the calculated sum is greater than the current max_sum.
  5. 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

View on GeeksforGeeks
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;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.