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

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find maximum sum such that no two elements are adjacent.

For this we will be provided with an array containing positive integers. Our task is to find the maximum sum subsequence such that they don’t have any two elements adjacent to each other.

Example

 Live Demo

#include <bits/stdc++.h>
#define maxLen 10
using namespace std;
int dp[maxLen];
bool v[maxLen];
//calculating the maximum subsequence
int maxSum(int arr[], int i, int n) {
   if (i >= n)
      return 0;
   if (v[i])
      return dp[i];
   v[i] = 1;
   dp[i] = max(maxSum(arr, i + 1, n),
   arr[i] + maxSum(arr, i + 2, n));
   return dp[i];
}
int main() {
   int arr[] = { 12, 9, 7, 33 };
   int n = sizeof(arr) / sizeof(int);
   cout << maxSum(arr, 0, n);
   return 0;
}

Output

45
raja
Published on 27-Jul-2020 11:55:26
Advertisements