Maximum sum such that no two elements are adjacent - Set 2 in C++


In this problem, we are given an array arr[]. Our task is to create a program to find the Maximum sum such that no two elements are adjacent in C++.

Problem Description

We need to find the maximum sum of the sequence from the array such that no 2 numbers from the sum sequence are adjacent in the array.

Let’s take an example to understand the problem,

Input

arr[] = {5, 1, 3, 7, 9, 2, 5}

Output

22

Explanation

Taking sum sequence from index 0 with alternate elements : 5 + 3 + 9 + 5 = 22
Taking sum sequence from index 1 with alternate elements : 1 + 7 + 2 = 10

Solution Approach

In the last set, we have seen one approach to solve the problem. Here, we will learn about the dynamic programming approach to solve the problem.

To solve the problem using the Dynamic Approach, we need to create a DP[] array that stores that max sum till the current index. And then find the sum index using this dynamic array.

The current DP max is the max of dp[i+2]+ arr[i] and dp[i+1].

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int DP[100];
bool currState[100];
int maxVal(int a, int b){
   if(a > b)
      return a;
      return b;
   }
int calcMaxSumWOAdj(int arr[], int i, int n){
   if (i >= n)
      return 0;
   if (currState[i])
      return DP[i];
   currState[i] = 1;
   DP[i] = maxVal(calcMaxSumWOAdj(arr, i + 1, n), arr[i] + calcMaxSumWOAdj(arr, i + 2, n));
   return DP[i];
}
int main(){
   int arr[] = { 5, 1, 3, 7, 9, 2, 5 };
   int n = sizeof(arr) / sizeof(int);
   cout<<"The maximum sum such that no two elements are adjacent is "<<calcMaxSumWOAdj(arr, 0, n);
   return 0;
}

Output

The maximum sum such that no two elements are adjacent is 22

Updated on: 15-Oct-2020

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements