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.
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.
- The robber has two options: to rob the current house (option “a”) or not to rob it (option “b”).
- If the robber chooses option “a”, they cannot rob the previous house (i-1), but can proceed to the one before that (i-2) and receive all the accumulated loot.
- If option “b” is selected, the robber will receive all the potential loot from the previous house (i-1) and all the houses before it.
- The decision of which option to choose ultimately comes down to determining which is more profitable: the loot obtained from the current house and previous houses before the one before the last, or the loot obtained from the previous house and all prior houses.
- The formula used to make this calculation is: rob(i) = Math.max( rob(i – 2) + currentHouseValue, rob(i – 1) ).
C++
#include <bits/stdc++.h>
using namespace std;
int rec(vector< int >& nums, int idx)
{
if (idx >= nums.size())
return 0;
return max(nums[idx] + rec(nums, idx + 2),
rec(nums, idx + 1));
}
int findMaxSum(vector< int > arr, int N)
{
return rec(arr, 0);
}
int main()
{
vector< int > arr = { 5, 5, 10, 100, 10, 5 };
int N = arr.size();
cout << findMaxSum(arr, N) << endl;
return 0;
}
|
C
#include <stdio.h>
int rec( int * nums, int idx, int size)
{
if (idx >= size)
return 0;
return (nums[idx] + rec(nums, idx + 2, size)
> rec(nums, idx + 1, size))
? nums[idx] + rec(nums, idx + 2, size)
: rec(nums, idx + 1, size);
}
int findMaxSum( int * arr, int N) { return rec(arr, 0, N); }
int main()
{
int arr[] = { 5, 5, 10, 100, 10, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
printf ( "%d" , findMaxSum(arr, N));
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int rec( int nums[], int idx, int N)
{
if (idx >= N)
return 0 ;
return Math.max(nums[idx] + rec(nums, idx + 2 , N),
rec(nums, idx + 1 , N));
}
static int findMaxSum( int [] arr, int N)
{
return rec(arr, 0 , N);
}
public static void main(String args[])
{
int [] arr = { 5 , 5 , 10 , 100 , 10 , 5 };
int N = 6 ;
System.out.println(findMaxSum(arr, N));
}
}
|
Python3
def rec(nums, idx):
if idx > = len (nums):
return 0
return max (nums[idx] + rec(nums, idx + 2 ), rec(nums, idx + 1 ))
def findMaxSum(arr, N):
return rec(arr, 0 )
if __name__ = = "__main__" :
arr = [ 5 , 5 , 10 , 100 , 10 , 5 ]
N = len (arr)
print (findMaxSum(arr, N))
|
C#
using System;
using System.Collections.Generic;
class Program
{
static int Rec(List< int > nums, int idx)
{
if (idx >= nums.Count)
return 0;
return Math.Max(nums[idx] + Rec(nums, idx + 2),
Rec(nums, idx + 1));
}
static int FindMaxSum(List< int > arr, int N)
{
return Rec(arr, 0);
}
static void Main( string [] args)
{
List< int > arr = new List< int >() { 5, 5, 10, 100, 10, 5 };
int N = arr.Count;
Console.WriteLine(FindMaxSum(arr, N));
}
}
|
Javascript
function rec(nums, idx)
{
if (idx >= nums.length)
return 0;
return Math.max(nums[idx] + rec(nums, idx + 2), rec(nums, idx + 1));
}
function findMaxSum(arr, N)
{
return rec(arr, 0);
}
arr = [5, 5, 10, 100, 10, 5];
N = arr.length;
console.log(findMaxSum(arr, N));
|
Time Complexity: O(2N) where N is the number of elements in A. At each index, we have two choices of either robbing or not robbing the current house. Thus this leads to a time complexity of 222…n times ≈ O(2^N)
Auxiliary Space: O(N) It is recursive stack space.
Maximum sum such that no two elements are adjacent using Dynamic Programming (Memoization):
We can cache the overlapping subproblems
C++
#include <bits/stdc++.h>
using namespace std;
int rec(vector< int >& nums, int idx, vector< int >& dp)
{
if (idx >= nums.size())
return 0;
if (dp[idx] != -1)
return dp[idx];
return dp[idx]
= max(rec(nums, idx + 1, dp),
nums[idx] + rec(nums, idx + 2, dp));
}
int findMaxSum(vector< int >& nums, int N)
{
vector< int > dp(N + 1, -1);
return rec(nums, 0, dp);
}
int main()
{
vector< int > arr = { 5, 5, 10, 100, 10, 5 };
int N = arr.size();
cout << findMaxSum(arr, N) << endl;
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
int rec( int * nums, int idx, int * dp, int size)
{
if (idx >= size)
return 0;
if (dp[idx] != -1)
return dp[idx];
return dp[idx]
= (rec(nums, idx + 1, dp, size)
> nums[idx] + rec(nums, idx + 2, dp, size))
? rec(nums, idx + 1, dp, size)
: nums[idx] + rec(nums, idx + 2, dp, size);
}
int findMaxSum( int * nums, int N)
{
int * dp = ( int *) malloc ((N + 1) * sizeof ( int ));
for ( int i = 0; i < N + 1; i++)
dp[i] = -1;
int result = rec(nums, 0, dp, N);
free (dp);
return result;
}
int main()
{
int arr[] = { 5, 5, 10, 100, 10, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
printf ( "%d\n" , findMaxSum(arr, N));
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int rec(List<Integer> nums, int idx, int [] dp) {
if (idx >= nums.size()) {
return 0 ;
}
if (dp[idx] != - 1 ) {
return dp[idx];
}
dp[idx] = Math.max(rec(nums, idx + 1 , dp), nums.get(idx) + rec(nums, idx + 2 , dp));
return dp[idx];
}
public static int findMaxSum(List<Integer> nums, int N) {
int [] dp = new int [N + 1 ];
Arrays.fill(dp, - 1 );
return rec(nums, 0 , dp);
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList( 5 , 5 , 10 , 100 , 10 , 5 );
int N = arr.size();
System.out.println(findMaxSum(arr, N));
}
}
|
Python3
def findMaxSum(nums, N):
dp = [ - 1 ] * (N + 1 )
def rec(idx, dp):
if idx > = len (nums):
return 0
if dp[idx] ! = - 1 :
return dp[idx]
dp[idx] = max (rec(idx + 1 , dp), nums[idx] + rec(idx + 2 , dp))
return dp[idx]
return rec( 0 , dp)
arr = [ 5 , 5 , 10 , 100 , 10 , 5 ]
N = len (arr)
print (findMaxSum(arr, N))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int Rec(List< int > nums, int idx, List< int > dp)
{
if (idx >= nums.Count)
return 0;
if (dp[idx] != -1)
return dp[idx];
return dp[idx]
= Math.Max(Rec(nums, idx + 1, dp),
nums[idx] + Rec(nums, idx + 2, dp));
}
static int FindMaxSum(List< int > nums, int N)
{
List< int > dp = new List< int >(N + 1);
for ( int i = 0; i <= N; i++)
{
dp.Add(-1);
}
return Rec(nums, 0, dp);
}
static void Main( string [] args)
{
List< int > arr = new List< int >() { 5, 5, 10, 100, 10, 5 };
int N = arr.Count;
Console.WriteLine(FindMaxSum(arr, N));
}
}
|
Javascript
function findMaxSum(nums, N) {
const dp = new Array(N + 1).fill(-1);
function rec(idx, dp) {
if (idx >= nums.length) {
return 0;
}
if (dp[idx] !== -1) {
return dp[idx];
}
dp[idx] = Math.max(rec(idx + 1, dp), nums[idx] + rec(idx + 2, dp));
return dp[idx];
}
return rec(0, dp);
}
const arr = [5, 5, 10, 100, 10, 5];
const N = arr.length;
console.log(findMaxSum(arr, N));
|
Time complexity: O(N) (recursion)
Space complexity: O(N)+O(N), one is recursive stack space and another O(N) is for dp array.
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++
#include <bits/stdc++.h>
using namespace std;
int findMaxSum(vector< int > arr, int N)
{
int dp[N][2];
if (N == 1) {
return arr[0];
}
dp[0][0] = 0;
dp[0][1] = arr[0];
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 max(dp[N - 1][0], dp[N - 1][1]);
}
int main()
{
vector< int > arr = { 5, 5, 10, 100, 10, 5 };
int N = arr.size();
cout << findMaxSum(arr, N) << endl;
return 0;
}
|
C
#include <stdio.h>
int findMaxSum( int arr[], int N)
{
int dp[N][2];
if (N == 1) {
return arr[0];
}
dp[0][0] = 0;
dp[0][1] = arr[0];
for ( int i = 1; i < N; i++) {
dp[i][1] = dp[i - 1][0] + arr[i];
dp[i][0] = (dp[i - 1][1] > dp[i - 1][0])
? dp[i - 1][1]
: dp[i - 1][0];
}
return (dp[N - 1][0] > dp[N - 1][1]) ? dp[N - 1][0]
: dp[N - 1][1];
}
int main()
{
int arr[] = { 5, 5, 10, 100, 10, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
printf ( "%d\n" , findMaxSum(arr, N));
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int findMaxSum( int [] arr, int N)
{
int [][] dp = new int [N][ 2 ];
if (N == 1 ) {
return arr[ 0 ];
}
dp[ 0 ][ 0 ] = 0 ;
dp[ 0 ][ 1 ] = arr[ 0 ];
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 Math.max(dp[N - 1 ][ 0 ], dp[N - 1 ][ 1 ]);
}
public static void main(String args[])
{
int [] arr = { 5 , 5 , 10 , 100 , 10 , 5 };
int N = arr.length;
System.out.println(findMaxSum(arr, N));
}
}
|
Python3
def findMaxSum(arr, N):
dp = [[ 0 for i in range ( 2 )] for j in range (N)]
if (N = = 1 ):
return arr[ 0 ]
dp[ 0 ][ 0 ] = 0
dp[ 0 ][ 1 ] = arr[ 0 ]
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 max (dp[N - 1 ][ 0 ], dp[N - 1 ][ 1 ])
arr = [ 5 , 5 , 10 , 100 , 10 , 5 ]
N = len (arr)
print (findMaxSum(arr, N))
|
C#
using System;
class GFG{
int findMaxSum( int [] arr, int n)
{
int [,] dp = new int [n,2];
if (n == 1) {
return arr[0];
}
dp[0,0] = 0;
dp[0,1] = arr[0];
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 Math.Max(dp[n - 1,0], dp[n - 1,1]);
}
static public void Main ()
{
GFG small = new GFG();
int [] arr = {5, 5, 10, 100, 10, 5};
int n = arr.Length;
Console.WriteLine(small.findMaxSum(arr,n));
}
}
|
Javascript
<script>
function findMaxSum(arr, N)
{
let dp = new Array(N);
for (let i = 0; i < N; i++)
{
dp[i] = new Array(2);
}
if (N == 1)
{
return arr[0];
}
dp[0][0] = 0;
dp[0][1] = arr[0];
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 Math.max(dp[N - 1][0], dp[N - 1][1]);
}
let arr = [ 5, 5, 10, 100, 10, 5 ];
let N = arr.length;
document.write(findMaxSum(arr, N), "</br>" );
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
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++) {
excl_new = max(incl, excl);
incl = excl + arr[i];
excl = excl_new;
}
return max(incl, excl);
}
int main()
{
vector< int > arr = { 5, 5, 10, 100, 10, 5 };
int N = arr.size();
cout << FindMaxSum(arr, N);
return 0;
}
|
C
#include <stdio.h>
int findMaxSum( int arr[], int n)
{
int incl = arr[0];
int excl = 0;
int excl_new;
int i;
for (i = 1; i < n; i++) {
excl_new = (incl > excl) ? incl : excl;
incl = excl + arr[i];
excl = excl_new;
}
return ((incl > excl) ? incl : excl);
}
int main()
{
int arr[] = { 5, 5, 10, 100, 10, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
printf ( "%d" , findMaxSum(arr, N));
return 0;
}
|
Java
import java.lang.*;
import java.util.*;
class MaximumSum {
int findMaxSum( int arr[], int n)
{
int incl = arr[ 0 ];
int excl = 0 ;
int excl_new;
int i;
for (i = 1 ; i < n; i++) {
excl_new = Math.max(incl, excl);
incl = excl + arr[i];
excl = excl_new;
}
return Math.max(incl, excl);
}
public static void main(String[] args)
{
MaximumSum sum = new MaximumSum();
int arr[] = new int [] { 5 , 5 , 10 , 100 ,
10 , 5 };
int N = arr.length;
System.out.println(
sum.findMaxSum(arr, arr.length));
}
}
|
Python3
def findMaxSum(arr, n):
incl = 0
excl = 0
for i in arr:
new_excl = max (excl, incl)
incl = excl + i
excl = new_excl
return max (excl, incl)
if __name__ = = "__main__" :
arr = [ 5 , 5 , 10 , 100 , 10 , 5 ]
N = 6
print (findMaxSum(arr, N))
|
C#
using System;
class GFG {
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++) {
excl_new = (incl > excl) ?
incl : excl;
incl = excl + arr[i];
excl = excl_new;
}
return ((incl > excl) ?
incl : excl);
}
public static void Main()
{
int []arr = new int []{5, 5, 10,
100, 10, 5};
int N = arr.Length;
Console.Write(findMaxSum(arr, N));
}
}
|
Javascript
<script>
function FindMaxSum(arr, n)
{
let incl = arr[0];
let excl = 0;
let excl_new;
let i;
for (i = 1; i < n; i++)
{
excl_new = (incl > excl) ? incl : excl;
incl = excl + arr[i];
excl = excl_new;
}
return ((incl > excl) ? incl : excl);
}
let arr = [ 5, 5, 10, 100, 10, 5 ];
document.write(FindMaxSum(arr, arr.length));
</script>
|
PHP
<?php
function FindMaxSum( $arr , $n )
{
$incl = $arr [0];
$excl = 0;
$excl_new ;
$i ;
for ( $i = 1; $i < $n ; $i ++)
{
$excl_new = ( $incl > $excl )? $incl : $excl ;
$incl = $excl + $arr [ $i ];
$excl = $excl_new ;
}
return (( $incl > $excl )? $incl : $excl );
}
$arr = array (5, 5, 10, 100, 10, 5);
$n = sizeof( $arr );
echo FindMaxSum( $arr , $n );
?>
|
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.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
14 Sep, 2023
Like Article
Save Article