Skip to content
Related Articles

Related Articles

Maximum sum such that no two elements are adjacent

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 28 Sep, 2022
Improve Article
Save Article

Given an array arr[] of positive numbers, The task is to find the maximum sum of a subsequence such that no 2 numbers in the sequence should be adjacent in the array.

Examples: 

Input: arr[] = {5, 5, 10, 100, 10, 5}
Output: 110
Explanation: Pick the subsequence {5, 100, 5}.
The sum is 110 and no two elements are adjacent. This is the highest possible sum.

Input: arr[] = {3, 2, 7, 10}
Output: 13
Explanation: The subsequence is {3, 10}. This gives sum = 13.
This is the highest possible sum of a subsequence following the given criteria

Input: arr[] = {3, 2, 5, 10, 7}
Output: 15
Explanation: Pick the subsequence {3, 5, 7}. The sum is 15.

Recommended Practice

Complete Interview Preparation - GFG

Naive Approach: Below is the idea to solve the problem:

Each element has two choices: either it can be the part of the subsequence with the highest sum or it cannot be part of the subsequence. So to solve the problem, build all the subsequences of the array and find the subsequence with the maximum sum such that no two adjacent elements are present in the subsequence.

Time Complexity: O(2N)
Auxiliary Space: O(N)

Maximum sum such that no two elements are adjacent using Dynamic Programming:

  • As seen above, each element has two choices. If one element is picked then its neighbours cannot be picked. Otherwise, its neighbours may be picked or may not be. 
  • So the maximum sum till ith index has two possibilities: the subsequence includes arr[i] or it does not include arr[i].
  • If arr[i] is included then the maximum sum depends on the maximum subsequence sum till (i-1)th element excluding arr[i-1].
  • Otherwise, the maximum sum is the same as the maximum subsequence sum till (i-1) where arr[i-1] may be included or excluded.

So build a 2D dp[N][2] array where dp[i][0] stores maximum subsequence sum till ith index with arr[i] excluded and dp[i][1] stores the sum when arr[i] is included.
The values will be obtained by the following relations: dp[i][1] = dp[i-1][0] + arr[i] and dp[i][0] = max(dp[i-1][0], dp[i-1][1])

Follow the steps mentioned below to implement the above idea:

  • If the size of the array is 1, then the answer is arr[0].
  • Initialize the values of dp[0][0] = 0 and dp[0][1] = arr[0].
  • Iterate from i = 1 to N-1:
    • Fill the dp array as per the relation shown above.
  • Return the maximum between dp[N-1][1] and dp[N-1][0] as that will be the answer.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum sum
int findMaxSum(vector<int> arr, int N)
{
    // Declare dp array
    int dp[N][2];
    if (N == 1) {
        return arr[0];
    }
   
    // Initialize the values in dp array
    dp[0][0] = 0;
    dp[0][1] = arr[0];
   
    // Loop to find the maximum possible sum
    for (int i = 1; i < N; i++) {
        dp[i][1] = dp[i - 1][0] + arr[i];
        dp[i][0] = max(dp[i - 1][1],
                       dp[i - 1][0]);
    }
   
    // Return the maximum sum
    return max(dp[N - 1][0], dp[N - 1][1]);
}
 
// Driver Code
int main()
{
    // Creating the array
    vector<int> arr = { 5, 5, 10, 100, 10, 5 };
    int N = arr.size();
 
    // Function call
    cout << findMaxSum(arr, N) << endl;
    return 0;
}

Java




/*package whatever //do not write package name here */
import java.io.*;
 
class GFG
{
 
  // Function to find the maximum sum
  static int findMaxSum(int[] arr, int N)
  {
    // Declare dp array
    int[][] dp = new int[N][2];
    if (N == 1) {
      return arr[0];
    }
 
    // Initialize the values in dp array
    dp[0][0] = 0;
    dp[0][1] = arr[0];
 
    // Loop to find the maximum possible sum
    for (int i = 1; i < N; i++) {
      dp[i][1] = dp[i - 1][0] + arr[i];
      dp[i][0] = Math.max(dp[i - 1][1],
                          dp[i - 1][0]);
    }
 
    // Return the maximum sum
    return Math.max(dp[N - 1][0], dp[N - 1][1]);
  }
 
 
  // Driver Code
  public static void main(String args[])
  {
 
    // Creating the array
    int[] arr = { 5, 5, 10, 100, 10, 5 };
    int N = arr.length;
 
    // Function call
    System.out.println(findMaxSum(arr, N));
  }
}
 
// This code is contributed by shinjanpatra

Python3




# Python code to implement the approach
 
# Function to find the maximum sum
def findMaxSum(arr, N):
 
    # Declare dp array
    dp = [[0 for i in range(2)] for j in range(N)]
     
    if (N == 1):
        return arr[0]
   
    # Initialize the values in dp array
    dp[0][0] = 0
    dp[0][1] = arr[0]
   
    # Loop to find the maximum possible sum
    for i in range(1,N):
        dp[i][1] = dp[i - 1][0] + arr[i]
        dp[i][0] = max(dp[i - 1][1], dp[i - 1][0])
   
    # Return the maximum sum
    return max(dp[N - 1][0], dp[N - 1][1])
 
# Driver Code
 
# Creating the array
arr = [ 5, 5, 10, 100, 10, 5 ]
N = len(arr)
 
# Function call
print(findMaxSum(arr, N))
 
# This code is contributed by shinjanpatra

C#




// C# program for above approach
using System;
 
class GFG{
     
// Function to find the maximum sum
int findMaxSum(int[] arr,int n)
{
     
    // Declare dp array
    int [,] dp = new int [n,2];
    if (n == 1) {
        return arr[0];
    }
    
    // Initialize the values in dp array
    dp[0,0] = 0;
    dp[0,1] = arr[0];
    
    // Loop to find the maximum possible sum
    for (int i = 1; i < n; i++) {
        dp[i,1] = dp[i - 1,0] + arr[i];
        dp[i,0] = Math.Max(dp[i - 1,1],
                       dp[i - 1,0]);
    }
    
    // Return the maximum sum
    return Math.Max(dp[n - 1,0], dp[n - 1,1]);
}
 
// Driver code
static public void Main ()
{
    GFG small = new GFG();
    int[] arr = {5, 5, 10, 100, 10, 5};
    int n = arr.Length;
     
    // Function Call
    Console.WriteLine(small.findMaxSum(arr,n));
}
}
 
// This code is contributed by Aarti_Rathi

Javascript




<script>
 
// JavaScript code to implement the approach
 
// Function to find the maximum sum
function findMaxSum(arr, N)
{
 
    // Declare dp array
    let dp = new Array(N);
    for(let i = 0; i < N; i++)
    {
        dp[i] = new Array(2);
    }
    if (N == 1)
    {
        return arr[0];
    }
   
    // Initialize the values in dp array
    dp[0][0] = 0;
    dp[0][1] = arr[0];
   
    // Loop to find the maximum possible sum
    for (let i = 1; i < N; i++) {
        dp[i][1] = dp[i - 1][0] + arr[i];
        dp[i][0] = Math.max(dp[i - 1][1],
                       dp[i - 1][0]);
    }
   
    // Return the maximum sum
    return Math.max(dp[N - 1][0], dp[N - 1][1]);
}
 
// Driver Code
 
// Creating the array
let arr = [ 5, 5, 10, 100, 10, 5 ];
let N = arr.length;
 
// Function call
document.write(findMaxSum(arr, N),"</br>");
 
/*This code is contribute by shinjanpatra */
 
</script>

Output

110

Time Complexity: O(N)
Auxiliary Space: O(N)

Space Optimized Approach: The above approach can be optimized to be done in constant space based on the following observation:

As seen from the previous dynamic programming approach, the value of current states (for ith element) depends upon only two states of the previous element. So instead of creating a 2D array, we can use only two variables to store the two states of the previous element.

  • Say excl stores the value of the maximum subsequence sum till i-1 when arr[i-1] is excluded and 
  • incl stores the value of the maximum subsequence sum till i-1 when arr[i-1] is included.
  • The value of excl for the current state( say excl_new) will be max(excl ,incl). And the value of incl will be updated to excl + arr[i].

Illustration:

Consider arr[] = {5,  5, 10, 100, 10, 5}

Initially at i = 0:  incl = 5, excl = 0

For i = 1: arr[i] = 5
        => excl_new = 5
        => incl = (excl + arr[i]) = 5
        => excl = excl_new = 5

For i = 2: arr[i] = 10
        => excl_new =  max(excl, incl) = 5
        => incl =  (excl + arr[i]) = 15
        => excl = excl_new = 5

For i = 3: arr[i] = 100
        => excl_new =  max(excl, incl) = 15
        => incl =  (excl + arr[i]) = 105
        => excl = excl_new = 15

For i = 4: arr[i] = 10
        => excl_new =  max(excl, incl) = 105
        => incl =  (excl + arr[i]) = 25
        => excl = excl_new = 105

For i = 5: arr[i] = 5
        => excl_new =  max(excl, incl) = 105
        => incl =  (excl + arr[i]) = 110
        => excl = excl_new = 105

So, answer is max(incl, excl) =  110

Follow the steps mentioned below to implement the above approach:

  • Initialize incl and excl with arr[0] and 0 respectively.
  • Iterate from i = 1 to N-1:
    • Update the values of incl and excl as mentioned above.
  • Return the maximum of incl and excl after the iteration is over as the answer.

Below is the implementation of the above approach.

C++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to return max sum such that
// no two elements are adjacent
int FindMaxSum(vector<int> arr, int n)
{
    int incl = arr[0];
    int excl = 0;
    int excl_new;
    int i;
 
    for (i = 1; i < n; i++) {
        // Current max excluding i
        excl_new = max(incl, excl);
 
        // Current max including i
        incl = excl + arr[i];
        excl = excl_new;
    }
 
    // Return max of incl and excl
    return max(incl, excl);
}
 
// Driver code
int main()
{
    vector<int> arr = { 5, 5, 10, 100, 10, 5 };
    int N = arr.size();
 
    // Function call
    cout << FindMaxSum(arr, N);
    return 0;
}
// This approach is contributed by Debanjan

C




// C code to implement the approach
 
#include <stdio.h>
 
// Function to return max sum such that
// no two elements are adjacent
int findMaxSum(int arr[], int n)
{
    int incl = arr[0];
    int excl = 0;
    int excl_new;
    int i;
 
    for (i = 1; i < n; i++) {
         
        // Current max excluding i
        excl_new = (incl > excl) ? incl : excl;
 
        // Current max including i
        incl = excl + arr[i];
        excl = excl_new;
    }
 
    // Return max of incl and excl
    return ((incl > excl) ? incl : excl);
}
 
// Driver code
int main()
{
    int arr[] = { 5, 5, 10, 100, 10, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
     
    // Function call
    printf("%d", findMaxSum(arr, N));
    return 0;
}

Java




// Java code to implement the approach
 
import java.lang.*;
import java.util.*;
 
class MaximumSum {
    // Function to return max sum such that
    // no two elements are adjacent
    int findMaxSum(int arr[], int n)
    {
        int incl = arr[0];
        int excl = 0;
        int excl_new;
        int i;
 
        for (i = 1; i < n; i++) {
            // Current max excluding i
            excl_new = Math.max(incl, excl);
 
            // Current max including i
            incl = excl + arr[i];
            excl = excl_new;
        }
 
        // Return max of incl and excl
        return Math.max(incl, excl);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        MaximumSum sum = new MaximumSum();
        int arr[] = new int[] { 5, 5, 10, 100,
                                10, 5 };
        int N = arr.length;
 
        // Function call
        System.out.println(
            sum.findMaxSum(arr, arr.length));
    }
}
 
// This code has been contributed by Mayank Jaiswal

Python3




# Python code to implement the approach
 
# Function to return max sum such that
# no two elements are adjacent
def findMaxSum(arr, n):
    incl = 0
    excl = 0  
    for i in arr:
         
        # Current max excluding i
        new_excl = max (excl, incl)
         
        # Current max including i
        incl = excl + i
        excl = new_excl
     
    # Return max of incl and excl
    return max(excl, incl)
 
# Driver code
if __name__ == "__main__":
    arr = [5, 5, 10, 100, 10, 5]
    N = 6
     
    # Function call
    print (findMaxSum(arr, N))
 
# This code is contributed by Kalai Selvan

C#




// C# code to implement the approach
 
using System;
 
class GFG {   
    // Function to return max sum such
    // that no two elements are adjacent
    static int findMaxSum(int []arr, int n)
    {
        int incl = arr[0];
        int excl = 0;
        int excl_new;
        int i;
 
        for (i = 1; i < n; i++) {
            // Current max excluding i
            excl_new = (incl > excl) ?
                            incl : excl;
 
            // Current max including i
            incl = excl + arr[i];
            excl = excl_new;
        }
 
        // Return max of incl and excl
        return ((incl > excl) ?
                            incl : excl);
    }
 
    // Driver code
    public static void Main()
    {
        int []arr = new int[]{5, 5, 10,
                              100, 10, 5};
        int N = arr.Length;
 
        // Function call
        Console.Write(findMaxSum(arr, N));
    }
}
 
// This code has been contributed by
// nitin mittal

PHP




<?php
// PHP code to find Maximum sum
// such that no two elements
// are adjacent
 
/* Function to return max sum
   such that no two elements
   are adjacent */
function FindMaxSum($arr, $n)
{
    $incl = $arr[0];
    $excl = 0;
    $excl_new;
    $i;
 
for ($i = 1; $i <$n; $i++)
{
     
    // current max excluding i
    $excl_new = ($incl > $excl)? $incl: $excl;
 
    // current max including i
    $incl = $excl + $arr[$i];
    $excl = $excl_new;
}
 
// return max of incl and excl
return (($incl > $excl)? $incl : $excl);
}
 
// Driver Code
$arr = array(5, 5, 10, 100, 10, 5);
$n = sizeof($arr);
echo FindMaxSum($arr, $n);
     
// This code is contributed by Ajit
?>

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to return max sum such that
// no two elements are adjacent
function FindMaxSum(arr, n)
{
    let incl = arr[0];
    let excl = 0;
    let excl_new;
    let i;
 
    for(i = 1; i < n; i++)
    {
         
        // Current max excluding i
        excl_new = (incl > excl) ? incl : excl;
 
        // Current max including i
        incl = excl + arr[i];
        excl = excl_new;
    }
 
    // Return max of incl and excl
    return ((incl > excl) ? incl : excl);
}
 
// Driver code
let arr = [ 5, 5, 10, 100, 10, 5 ];
 
document.write(FindMaxSum(arr, arr.length));
 
// This code is contributed by Mayank Tyagi
 
</script>

Output

110

Time Complexity: O(N)
Auxiliary Space: O(1).

Similar problem: Find maximum possible stolen value from houses
Please write comments if you find any bug in the above program/algorithm or other ways to solve the same problem.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!