Maximum sum such that no two are adjacent
Last Updated :
07 Apr, 2025
Given an array of positive numbers, find the maximum sum of a subsequence such that no two numbers in the subsequence 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 the highest possible sum = 13.
Input: arr[] = {3, 2, 5, 10, 7}
Output: 15
Explanation: Pick the subsequence {3, 5, 7}. The sum is 15.
[Naive Approach] Using Recursion- O(2^n) Time and O(n) Space
The idea is to explore all the possibilities for each element using Recursion. We can start from the last element and for each element, we have two choices:
- Pick the current element and skip the element just before it.
- Skip the current element and move to the element just before it.
So, the recurrence relation will be:
maxSumRec(n) = max(arr[n - 1] + maxSumRec(n - 2),
maxSumRec(n - 1)),
where maxSumRec(n) returns the maximum sum if n elements are left.
C++
// C++ Program to find maximum sum with no two adjacent using Recursion
#include <iostream>
#include <vector>
using namespace std;
// Calculate the maximum Sum value recursively
int maxSumRec(vector<int> &arr, int n) {
// If no elements are left, return 0.
if (n <= 0) return 0;
// If only 1 element is left, pick it.
if (n == 1) return arr[0];
// Two Choices: pick the nth element and do not pick the nth element
int pick = arr[n - 1] + maxSumRec(arr, n - 2);
int notPick = maxSumRec(arr, n - 1);
// Return the max of two choices
return max(pick, notPick);
}
// Function to calculate the maximum Sum value
int maxSum(vector<int>& arr) {
int n = arr.size();
// Call the recursive function for n elements
return maxSumRec(arr, n);
}
int main() {
vector<int> arr = {6, 7, 1, 3, 8, 2, 4};
cout << maxSum(arr);
return 0;
}
C
// C Program to find maximum sum with no two adjacent using Recursion
#include <stdio.h>
// Function to calculate the maximum Sum value
int maxSum(int *arr, int n) {
// If no elements are left, return 0.
if (n <= 0) return 0;
// If only 1 element is left, pick it.
if (n == 1) return arr[0];
// Two Choices: pick the nth element and do not pick the nth element
int pick = arr[n - 1] + maxSum(arr, n - 2);
int notPick = maxSum(arr, n - 1);
// Return the max of two choices
return (pick > notPick) ? pick : notPick;
}
int main() {
int arr[] = {6, 7, 1, 3, 8, 2, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", maxSum(arr, n));
return 0;
}
Java
// Java Program to find maximum sum with no two adjacent using Recursion
class GfG {
// Calculate the maximum Sum value recursively
static int maxSumRec(int[] arr, int n) {
// If no elements are left, return 0.
if (n <= 0) return 0;
// If only 1 element is left, pick it.
if (n == 1) return arr[0];
// Two Choices: pick the nth element and do not pick the nth element
int pick = arr[n - 1] + maxSumRec(arr, n - 2);
int notPick = maxSumRec(arr, n - 1);
// Return the max of two choices
return Math.max(pick, notPick);
}
// Function to calculate the maximum Sum value
static int maxSum(int[] arr) {
int n = arr.length;
// Call the recursive function for n elements
return maxSumRec(arr, n);
}
public static void main(String[] args) {
int[] arr = {6, 7, 1, 3, 8, 2, 4};
System.out.println(maxSum(arr));
}
}
Python
# Python Program to find maximum sum with no two adjacent using Recursion
# Calculate the maximum Sum value recursively
def maxSumRec(arr, n):
# If no elements are left, return 0.
if n <= 0:
return 0
# If only 1 element is left, pick it.
if n == 1:
return arr[0]
# Two Choices: pick the nth element and do not pick the nth element
pick = arr[n - 1] + maxSumRec(arr, n - 2)
notPick = maxSumRec(arr, n - 1)
# Return the max of two choices
return max(pick, notPick)
# Function to calculate the maximum Sum value
def maxSum(arr):
n = len(arr)
# Call the recursive function for n elements
return maxSumRec(arr, n)
if __name__ == "__main__":
arr = [6, 7, 1, 3, 8, 2, 4]
print(maxSum(arr))
C#
// C# Program to find maximum sum with no two adjacent using Recursion
using System;
class GfG {
// Calculate the maximum Sum value recursively
static int maxSumRec(int[] arr, int n) {
// If no elements are left, return 0.
if (n <= 0) return 0;
// If only 1 element is left, pick it.
if (n == 1) return arr[0];
// Two Choices: pick the nth element and do not pick the nth element
int pick = arr[n - 1] + maxSumRec(arr, n - 2);
int notPick = maxSumRec(arr, n - 1);
// Return the max of two choices
return Math.Max(pick, notPick);
}
// Function to calculate the maximum Sum value
static int maxSum(int[] arr) {
int n = arr.Length;
// Call the recursive function for n elements
return maxSumRec(arr, n);
}
static void Main() {
int[] arr = { 6, 7, 1, 3, 8, 2, 4 };
Console.WriteLine(maxSum(arr));
}
}
JavaScript
// JavaScript Program to find maximum sum with no two adjacent using Recursion
// Calculate the maximum Sum value recursively
function maxSumRec(arr, n) {
// If no elements are left, return 0.
if (n <= 0) return 0;
// If only 1 element is left, pick it.
if (n === 1) return arr[0];
// Two Choices: pick the nth element and do not pick the nth element
let pick = arr[n - 1] + maxSumRec(arr, n - 2);
let notPick = maxSumRec(arr, n - 1);
// Return the max of two choices
return Math.max(pick, notPick);
}
// Function to calculate the maximum Sum value
function maxSum(arr) {
let n = arr.length;
// Call the recursive function for n elements
return maxSumRec(arr, n);
}
let arr = [6, 7, 1, 3, 8, 2, 4];
console.log(maxSum(arr));
Time Complexity: O(2n). Every element has 2 choices to pick and not pick.
Auxiliary Space: O(n). For recursion stack space
[Better Approach] Using Memoization - O(n) Time and O(n) Space
The above solution has optimal substructure and overlapping subproblems.
We can optimize this solution using a memo array of size (n + 1), such that memo[i] represents the maximum value that can be collected from first i elements. Please note that there is only one parameter that changes in recursion and the range of this parameter is from 0 to n.
C++
// C++ Program to find maximum sum with no two adjacent
#include <iostream>
#include <vector>
using namespace std;
int maxSumRec(vector<int>& arr, int n, vector<int>& memo) {
if (n <= 0) return 0;
if (n == 1) return arr[0];
// Check if the result is already computed
if (memo[n] != -1) return memo[n];
int pick = arr[n - 1] + maxSumRec(arr, n - 2, memo);
int notPick = maxSumRec(arr, n - 1, memo);
// Store the max of two choices in the memo array and return it
memo[n] = max(pick, notPick);
return memo[n];
}
int maxSum(vector<int>& arr) {
int n = arr.size();
// Initialize memo array with -1
vector<int> memo(n + 1, -1);
return maxSumRec(arr, n, memo);
}
int main() {
vector<int> arr = {6, 7, 1, 3, 8, 2, 4};
cout << maxSum(arr);
return 0;
}
C
// C Program to find maximum sum with no two adjacent
#include <stdio.h>
#include <stdlib.h>
int maxSumRec(const int* arr, int n, int* memo) {
if (n <= 0) return 0;
if (n == 1) return arr[0];
// Check if the result is already computed
if (memo[n] != -1) return memo[n];
int pick = arr[n - 1] + maxSumRec(arr, n - 2, memo);
int notPick = maxSumRec(arr, n - 1, memo);
// Store the max of two choices in the memo array and return it
memo[n] = (pick > notPick) ? pick : notPick;
return memo[n];
}
int maxSum(int* arr, int n) {
// Initialize memo array with -1
int memo[n + 1];
for (int i = 0; i <= n; ++i) {
memo[i] = -1;
}
int result = maxSumRec(arr, n, memo);
return result;
}
int main() {
int arr[] = {6, 7, 1, 3, 8, 2, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", maxSum(arr, n));
return 0;
}
Java
// Java Program to find maximum sum with no two adjacent
import java.util.Arrays;
class GfG {
static int maxSumRec(int[] arr, int n, int[] memo) {
if (n <= 0) return 0;
if (n == 1) return arr[0];
// Check if the result is already computed
if (memo[n] != -1) return memo[n];
int pick = arr[n - 1] + maxSumRec(arr, n - 2, memo);
int notPick = maxSumRec(arr, n - 1, memo);
// Store the max of two choices in the memo array and return it
memo[n] = Math.max(pick, notPick);
return memo[n];
}
// Function to calculate the maximum Sum value
static int maxSum(int[] arr) {
int n = arr.length;
// Initialize memo array with -1
int[] memo = new int[n + 1];
Arrays.fill(memo, -1);
return maxSumRec(arr, n, memo);
}
public static void main(String[] args) {
int[] arr = {6, 7, 1, 3, 8, 2, 4};
System.out.println(maxSum(arr));
}
}
Python
# Python Program to find maximum sum with no two adjacent
def maxSumRec(arr, n, memo):
if n <= 0:
return 0
if n == 1:
return arr[0]
# Check if the result is already computed
if memo[n] != -1:
return memo[n]
pick = arr[n - 1] + maxSumRec(arr, n - 2, memo)
notPick = maxSumRec(arr, n - 1, memo)
# Store the max of two choices in the memo array and return it
memo[n] = max(pick, notPick)
return memo[n]
def maxSum(arr):
n = len(arr)
# Initialize memo array with -1
memo = [-1] * (n + 1)
return maxSumRec(arr, n, memo)
if __name__ == "__main__":
arr = [6, 7, 1, 3, 8, 2, 4]
print(maxSum(arr))
C#
// C# Program to find maximum sum with no two adjacent
using System;
class GfG {
static int maxSumRec(int[] arr, int n, int[] memo) {
if (n <= 0) return 0;
if (n == 1) return arr[0];
// Check if the result is already computed
if (memo[n] != -1) return memo[n];
int pick = arr[n - 1] + maxSumRec(arr, n - 2, memo);
int notPick = maxSumRec(arr, n - 1, memo);
// Store the max of two choices in the memo array and return it
memo[n] = Math.Max(pick, notPick);
return memo[n];
}
// Function to calculate the maximum Sum value
static int maxSum(int[] arr) {
int n = arr.Length;
// Initialize memo array with -1
int[] memo = new int[n + 1];
for (int i = 0; i <= n; i++) {
memo[i] = -1;
}
return maxSumRec(arr, n, memo);
}
static void Main() {
int[] arr = { 6, 7, 1, 3, 8, 2, 4 };
Console.WriteLine(maxSum(arr));
}
}
JavaScript
// JS Program to find maximum sum with no two adjacent
function maxSumRec(arr, n, memo) {
if (n <= 0) return 0;
if (n === 1) return arr[0];
// Check if the result is already computed
if (memo[n] !== -1) return memo[n];
const pick = arr[n - 1] + maxSumRec(arr, n - 2, memo);
const notPick = maxSumRec(arr, n - 1, memo);
// Store the max of two choices in the memo array and return it
memo[n] = Math.max(pick, notPick);
return memo[n];
}
// Function to calculate the maximum Sum value
function maxSum(arr) {
const n = arr.length;
// Initialize memo array with -1
const memo = new Array(n + 1).fill(-1);
return maxSumRec(arr, n, memo);
}
const arr = [6, 7, 1, 3, 8, 2, 4];
console.log(maxSum(arr));
Time Complexity: O(n). Every element is computed only once.
Auxiliary Space: O(n). For recursion stack space and memo array.
[Expected Approach 1] Using Tabulation - O(n) Time and O(n) Space
The idea is to build the solution in bottom-up manner. We create a dp[] array of size n+1 where dp[i] represents the maximum sum that can be obtained with first i elements. We first fill the known values, dp[0] and dp[1] and then fill the remaining values using the formula: dp[i] = max(arr[i] + dp[i - 2], dp[i - 1]). The final result will be stored at dp[n].
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to calculate the maximum Sum value using bottom-up DP
int maxSum(vector<int>& arr) {
int n = arr.size();
// Create a dp array to store the maximum sum at each element
vector<int> dp(n+1, 0);
// Base cases
dp[0] = 0;
dp[1] = arr[0];
// Fill the dp array using the bottom-up approach
for (int i = 2; i <= n; i++)
dp[i] = max(arr[i - 1] + dp[i - 2], dp[i - 1]);
return dp[n];
}
int main() {
vector<int> arr = {6, 7, 1, 3, 8, 2, 4};
cout << maxSum(arr) << endl;
return 0;
}
C
#include <stdio.h>
int max(int a, int b) {return (a > b) ? a : b;}
int maxSum(int* arr, int n) {
// Create a dp array to store the
// maximum sum at each element
int dp[n+1];
dp[0] = 0;
dp[1] = arr[0];
// Fill the dp array using the
// bottom-up approach
for (int i = 2; i <= n; i++)
dp[i] = max(arr[i - 1] + dp[i - 2], dp[i - 1]);
return dp[n];
}
int main() {
int arr[] = {6, 7, 1, 3, 8, 2, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", maxSum(arr, n));
return 0;
}
Java
class GfG {
// Function to calculate the maximum Sum value using bottom-up DP
static int maxSum(int[] arr) {
int n = arr.length;
// Create a dp array to store the maximum sum at each element
int[] dp = new int[n + 1];
// Base cases
dp[0] = 0;
dp[1] = arr[0];
// Fill the dp array using the bottom-up approach
for (int i = 2; i <= n; i++) {
dp[i] = Math.max(arr[i - 1] + dp[i - 2], dp[i - 1]);
}
return dp[n];
}
public static void main(String[] args) {
int[] arr = {6, 7, 1, 3, 8, 2, 4};
System.out.println(maxSum(arr));
}
}
Python
def maxSum(arr):
n = len(arr)
# Create a dp array to store the maximum sum at each element
dp = [0] * (n + 1)
# Base cases
dp[0] = 0
dp[1] = arr[0]
# Fill the dp array using the bottom-up approach
for i in range(2, n + 1):
dp[i] = max(arr[i - 1] + dp[i - 2], dp[i - 1])
return dp[n]
arr = [6, 7, 1, 3, 8, 2, 4]
print(maxSum(arr))
C#
using System;
class GfG {
// Function to calculate the maximum Sum value using bottom-up DP
static int maxSum(int[] arr) {
int n = arr.Length;
// Create a dp array to store the maximum sum at each element
int[] dp = new int[n + 1];
// Base cases
dp[0] = 0;
dp[1] = arr[0];
// Fill the dp array using the bottom-up approach
for (int i = 2; i <= n; i++) {
dp[i] = Math.Max(arr[i - 1] + dp[i - 2], dp[i - 1]);
}
return dp[n];
}
static void Main() {
int[] arr = { 6, 7, 1, 3, 8, 2, 4 };
Console.WriteLine(maxSum(arr));
}
}
JavaScript
function maxSum(arr) {
const n = arr.length;
// Create a dp array to store the maximum sum at each element
const dp = new Array(n + 1).fill(0);
// Base cases
dp[0] = 0;
dp[1] = arr[0];
// Fill the dp array using the bottom-up approach
for (let i = 2; i <= n; i++)
dp[i] = Math.max(arr[i - 1] + dp[i - 2], dp[i - 1]);
return dp[n];
}
const arr = [6, 7, 1, 3, 8, 2, 4];
console.log(maxSum(arr));
Time Complexity: O(n), Every element is computed only once.
Auxiliary Space O(n), We are using a dp array of size n.
[Expected Approach 2] Space-Optimized DP - O(n) Time and O(1) Space
On observing the dp[] array in the previous approach, it can be seen that the answer at the current index depends only on the last two values. In other words, dp[i] depends only on dp[i - 1] and dp[i - 2]. So, instead of storing the result in an array, we can simply use two variables to store the last and second last result.
C++
#include <iostream>
#include <vector>
using namespace std;
// Function to calculate the maximum Sum value
int maxSum(vector<int> &arr) {
int n = arr.size();
if (n == 0)
return 0;
if (n == 1)
return arr[0];
// Set previous 2 values
int secondLast = 0, last = arr[0];
// Compute current value using previous two values
// The final current value would be our result
int res;
for (int i = 1; i < n; i++) {
res = max(arr[i] + secondLast, last);
secondLast = last;
last = res;
}
return res;
}
int main() {
vector<int> arr = {6, 7, 1, 3, 8, 2, 4};
cout << maxSum(arr) << endl;
return 0;
}
C
#include <stdio.h>
int max(int a, int b) { return (a > b) ? a : b; }
// Function to calculate the maximum Sum value
int maxSum(int arr[], int n) {
if (n == 0)
return 0;
if (n == 1)
return arr[0];
// Set previous 2 values
int secondLast = 0, last = arr[0];
// Compute current value using previous
// two values. The final current value
// would be our result
int res;
for (int i = 1; i < n; i++) {
res = max(arr[i] + secondLast, last);
secondLast = last;
last = res;
}
return res;
}
int main() {
int arr[] = {6, 7, 1, 3, 8, 2, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", maxSum(arr, n));
return 0;
}
Java
import java.util.Arrays;
class GfG {
// Function to calculate the maximum Sum value
static int maxSum(int[] arr) {
int n = arr.length;
if (n == 0)
return 0;
if (n == 1)
return arr[0];
// Set previous 2 values
int secondLast = 0, last = arr[0];
// Compute current value using previous
// two values. The final current value
// would be our result
int res = 0;
for (int i = 1; i < n; i++) {
res = Math.max(arr[i] + secondLast, last);
secondLast = last;
last = res;
}
return res;
}
public static void main(String[] args) {
int[] arr = {6, 7, 1, 3, 8, 2, 4};
System.out.println(maxSum(arr));
}
}
Python
# Function to calculate the maximum Sum value
def maxSum(arr):
n = len(arr)
if n == 0:
return 0
if n == 1:
return arr[0]
# Set previous 2 values
secondLast = 0
last = arr[0]
# Compute current value using previous two values
# The final current value would be our result
res = 0
for i in range(1, n):
res = max(arr[i] + secondLast, last)
secondLast = last
last = res
return res
arr = [6, 7, 1, 3, 8, 2, 4]
print(maxSum(arr))
C#
using System;
class GfG {
// Function to calculate the maximum Sum value
static int maxSum(int[] arr) {
int n = arr.Length;
if (n == 0)
return 0;
if (n == 1)
return arr[0];
// Set previous 2 values
int secondLast = 0, last = arr[0];
// Compute current value using previous two values
// The final current value would be our result
int res = 0;
for (int i = 1; i < n; i++) {
res = Math.Max(arr[i] + secondLast, last);
secondLast = last;
last = res;
}
return res;
}
static void Main() {
int[] arr = { 6, 7, 1, 3, 8, 2, 4 };
Console.WriteLine(maxSum(arr));
}
}
JavaScript
// Function to calculate the maximum Sum value
function maxSum(arr) {
const n = arr.length;
if (n === 0)
return 0;
if (n === 1)
return arr[0];
// Set previous 2 values
let secondLast = 0, last = arr[0];
// Compute current value using previous two values
// The final current value would be our result
let res;
for (let i = 1; i < n; i++) {
res = Math.max(arr[i] + secondLast, last);
secondLast = last;
last = res;
}
return res;
}
const arr = [6, 7, 1, 3, 8, 2, 4];
console.log(maxSum(arr));
Time Complexity: O(n), Every value is computed only once.
Auxiliary Space: O(1), as we are using only two variables.
Similar Reads
Maximum sum of nodes in Binary tree such that no two are adjacent
Given a binary tree with a value associated with each node, we need to choose a subset of these nodes such that the sum of selected nodes is maximum under a constraint that no two chosen nodes in the subset should be directly connected, that is, if we have taken a node in our sum then we canât take
15+ min read
Maximum sum in circular array such that no two elements are adjacent
You are given an array arr[] which represents houses arranged in a circle, where each house has a certain value. A thief aims to maximize the total stolen value without robbing two adjacent houses. Since the houses are in a circle, the first and last houses are also considered adjacent. The task is
15+ min read
Maximum sum such that exactly half of the elements are selected and no two adjacent
Given an array A containing N integers. Find the maximum sum possible such that exact floor(N/2) elements are selected and no two selected elements are adjacent to each other. (if N = 5, then exactly 2 elements should be selected as floor(5/2) = 2) For a simpler version of this problem check out thi
14 min read
Maximum subsequence sum such that no three are consecutive
Given a sequence of positive numbers, find the maximum sum that can be formed which has no three consecutive elements present.Examples : Input: arr[] = {1, 2, 3}Output: 5We can't take three of them, so answer is2 + 3 = 5Input: arr[] = {3000, 2000, 1000, 3, 10}Output: 5013 3000 + 2000 + 3 + 10 = 5013
14 min read
Maximum Sum pair of non adjacent elements in array
Given an array arr[] of distinct Integers, find the pair with maximum sum such that both elements of the pair are not adjacent in the array Examples: Input: arr[] = {7, 3, 4, 1, 8, 9}Output: 9 7Explanation: Pair with maximum sum is (8, 9). But since both elements are adjacent, it is not a valid pair
8 min read
Maximum sum in an array such that every element has exactly one adjacent element to it
Given an array arr[] of N integers, you can select some indexes such that every selected index has exactly one other selected index adjacent to it and the sum of elements at the chosen indexes should be maximum. In other words, the task is to select elements from an array such that a single element
9 min read
Longest sequence such that no two adjacent element are of same type
Given an array arr[] of size N, where each value represents the number of elements present of the ith type, the task is to find the longest sequence that can be made such that no two adjacent elements are of the same type. Examples: Input: N = 3, arr[] = {7, 3, 2}Output: 11Explanation:In the above e
8 min read
Maximum sum of difference of adjacent elements
Given a number n. We have to find maximum sum of all permutations of n. The maximum sum will be sum of absolute difference of adjacent elements in array. Examples: Input : 3 Output : 3 Permutations of size 3 are: {1, 2, 3} = 1 + 1 {1, 3, 2} = 2 + 1 {2, 1, 3} = 1 + 2 {2, 3, 1} = 1 + 2 {3, 1, 2} = 2 +
4 min read
Modify array to maximize sum of adjacent differences
Given an array, we need to modify the values of this array in such a way that the sum of absolute differences between two consecutive elements is maximized. If the value of an array element is X, then we can change it to either 1 or X. Examples : Input : arr[] = [3, 2, 1, 4, 5] Output : 8 We can mod
9 min read
Maximum subsequence sum such that no K elements are consecutive
Given an array arr[] of N positive integers, the task is to find the maximum sum of a subsequence consisting of no K consecutive array elements. Examples: Input: arr[] = {10, 5, 8, 16, 21}, K = 4Output: 55Explanation:Maximum sum is obtained by picking 10, 8, 16, 21. Input: arr[] = {4, 12, 22, 18, 34
9 min read