Maximum sum such that no two elements are adjacent | Set 2

Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return 15 (sum of 3, 5 and 7).

Examples:

Input :  arr[] = {3, 5, 3} 
Output : 6 
Explanation : 
Selecting indexes 0 and 2 will maximise the sum 
i.e 3+3 = 6

Input : arr[] = {2, 5, 2}
Output : 5

We have already discussed the efficient approach of solving this problem in the previous article.



However, we can also solve this problem using Dynamic Programming approach.

Dynamic Programming Approach: Let’s decide the states of ‘dp’. Let dp[i] be the largest possible sum for the sub-array staring from index ‘i’ and ending at index ‘N-1’. Now, we have to find a recurrence relation between this state and a lower-order state.

In this case for an index ‘i’, we will have two choices.

1) Choose the current index:
   In this case, the relation will be dp[i] = arr[i] + dp[i+2]
2) Skip the current index:
   Relation will be dp[i] = dp[i+1]

We will choose the path that maximizes our result.
Thus final relation will be:

dp[i] = max(dp[i+2]+arr[i], dp[i+1])

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement above approach
  
#include <bits/stdc++.h>
#define maxLen 10
using namespace std;
  
// variable to store states of dp
int dp[maxLen];
  
// variable to check if a given state
// has been solved
bool v[maxLen];
  
// Function to find the maximum sum subsequence
// such that no two elements are adjacent
int maxSum(int arr[], int i, int n)
{
    // Base case
    if (i >= n)
        return 0;
  
    // To check if a state has
    // been solved
    if (v[i])
        return dp[i];
    v[i] = 1;
  
    // Required recurrence relation
    dp[i] = max(maxSum(arr, i + 1, n),
                arr[i] + maxSum(arr, i + 2, n));
  
    // Returning the value
    return dp[i];
}
  
// Driver code
int main()
{
    int arr[] = { 12, 9, 7, 33 };
  
    int n = sizeof(arr) / sizeof(int);
  
    cout << maxSum(arr, 0, n);
  
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement above approach 
class GFG
{
  
static int maxLen = 10;
  
// variable to store states of dp 
static int dp[] = new int[maxLen]; 
  
// variable to check if a given state 
// has been solved 
static boolean v[] = new boolean[maxLen]; 
  
// Function to find the maximum sum subsequence 
// such that no two elements are adjacent 
static int maxSum(int arr[], int i, int n) 
    // Base case 
    if (i >= n) 
        return 0
  
    // To check if a state has 
    // been solved 
    if (v[i]) 
        return dp[i]; 
    v[i] = true
  
    // Required recurrence relation 
    dp[i] = Math.max(maxSum(arr, i + 1, n), 
                arr[i] + maxSum(arr, i + 2, n)); 
  
    // Returning the value 
    return dp[i]; 
  
// Driver code 
public static void main(String args[])
    int arr[] = { 12, 9, 7, 33 }; 
    int n = arr.length; 
    System.out.println( maxSum(arr, 0, n)); 
}
}
  
// This code is contributed by Arnab Kundu
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to implement above approach
maxLen = 10
  
# variable to store states of dp
dp = [0 for i in range(maxLen)]
  
# variable to check if a given state 
# has been solved
v = [0 for i in range(maxLen)]
  
# Function to find the maximum sum subsequence
# such that no two elements are adjacent
def maxSum(arr, i, n):
    # Base case
    if (i >= n):
        return 0
  
    # To check if a state has
    # been solved
    if (v[i]):
        return dp[i]
    v[i] = 1
  
    # Required recurrence relation
    dp[i] = max(maxSum(arr, i + 1, n),
            arr[i] + maxSum(arr, i + 2, n))
  
    # Returning the value
    return dp[i]
  
# Driver code
if __name__ == '__main__':
    arr = [12, 9, 7, 33]
  
    n = len(arr)
    print(maxSum(arr, 0, n))
  
# This code is contributed by
# Surendra_Gangwar
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement above approach 
using System;
  
class GFG
{
  
static int maxLen = 10;
  
// variable to store states of dp 
static int[] dp = new int[maxLen]; 
  
// variable to check if a given state 
// has been solved 
static bool[] v = new bool[maxLen]; 
  
// Function to find the maximum sum subsequence 
// such that no two elements are adjacent 
static int maxSum(int[] arr, int i, int n) 
    // Base case 
    if (i >= n) 
        return 0; 
  
    // To check if a state has 
    // been solved 
    if (v[i]) 
        return dp[i]; 
    v[i] = true
  
    // Required recurrence relation 
    dp[i] = Math.Max(maxSum(arr, i + 1, n), 
                arr[i] + maxSum(arr, i + 2, n)); 
  
    // Returning the value 
    return dp[i]; 
  
// Driver code 
public static void Main()
    int[] arr = { 12, 9, 7, 33 }; 
    int n = arr.Length; 
    Console.Write( maxSum(arr, 0, n)); 
}
}
  
// This code is contributed by ChitraNayal
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to implement above approach 
  
$maxLen = 10; 
  
// variable to store states of dp 
$dp = array_fill(0, $GLOBALS['maxLen'], 0); 
  
// variable to check if a given state 
// has been solved 
$v = array_fill(0, $GLOBALS['maxLen'], 0); 
  
// Function to find the maximum sum subsequence 
// such that no two elements are adjacent 
function maxSum($arr, $i, $n
    // Base case 
    if ($i >= $n
        return 0; 
  
    // To check if a state has 
    // been solved 
    if ($GLOBALS['v'][$i]) 
        return $GLOBALS['dp'][$i]; 
          
    $GLOBALS['v'][$i] = 1; 
  
    // Required recurrence relation 
    $GLOBALS['dp'][$i] = max(maxSum($arr, $i + 1, $n), 
                $arr[$i] + maxSum($arr, $i + 2, $n)); 
  
    // Returning the value 
    return $GLOBALS['dp'][$i]; 
  
    // Driver code 
    $arr = array( 12, 9, 7, 33 ); 
  
    $n = count($arr); 
  
    echo maxSum($arr, 0, $n); 
  
    // This code is contributed by AnkitRai01
?>
chevron_right

Output:
45

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :