Maximum sum such that no two elements are adjacent - GeeksforGeeks

26 Apr, 2022
Given an array arr[] of positive numbers, the task is to find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array.
Examples: 
Input: arr[] = {5, 5, 10, 100, 10, 5}Output: 110Explanation: 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: 13Explanation: 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: 15Explanation: Pick the subsequence {3, 5, 7}. The sum is 15.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Naive Approach: 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(1)
Efficient Approach: This problem can be solved using Dynamic Programming based on the following idea:
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.
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++
Python3
Javascript
// C++ code to implement the approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum sumint 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 Codeint 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;}
# Python code to implement the approach # Function to find the maximum sumdef 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 arrayarr = [ 5, 5, 10, 100, 10, 5 ]N = len(arr) # Function callprint(findMaxSum(arr, N)) # This code is contribute by shinjanpatra
<script> // JavaScript code to implement the approach // Function to find the maximum sumfunction 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 arraylet arr = [ 5, 5, 10, 100, 10, 5 ];let N = arr.length; // Function calldocument.write(findMaxSum(arr, N),"</br>"); /*This code is contribute by shinjanpatra */ </script>
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 subequence 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].
Follow the illustration below for a better understanding:
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.
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
Java
Python3
C#
PHP
Javascript
// 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 adjacentint 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 codeint 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 code to implement the approach #include <stdio.h> // Function to return max sum such that// no two elements are adjacentint 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 codeint 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 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
# Python code to implement the approach # Function to return max sum such that# no two elements are adjacentdef 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 codeif __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# 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 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 exclreturn (($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?>
<script> // Javascript program for the above approach // Function to return max sum such that// no two elements are adjacentfunction 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 codelet arr = [ 5, 5, 10, 100, 10, 5 ]; document.write(FindMaxSum(arr, arr.length)); // This code is contributed by Mayank Tyagi </script>
110
Time Complexity: O(N)Auxiliary Space: O(1).
YouTubeGeeksforGeeks507K subscribersMaximum sum such that no two elements are adjacent | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:25•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=6w60Zi1NtL8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Similar problem: Find maximum possible stolen value from housesPlease write comments if you find any bug in the above program/algorithm or other ways to solve the same problem.
jit_t
nitin mittal
RimjhimBhadani
mohit kumar 29
mayanktyagi1709
noah28
amartyaghoshgfg
GauravRajput1
code_hunt
rohitsingh07052
shinjanpatra
animeshdey
sweetyty
Accolite
Amazon
Oxigen Wallet
OYO Rooms
Paytm
Walmart
Yahoo
Arrays
Dynamic Programming
Paytm
Accolite
Amazon
OYO Rooms
Walmart
Oxigen Wallet
Yahoo
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays in C/C++
Write a program to reverse an array or string
Program for array rotation
Largest Sum Contiguous Subarray
0-1 Knapsack Problem | DP-10
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23