
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Sum Such That No Two Elements Are Adjacent in C++
In this problem, we are given an array arr[] of size n consisting of positive values. Our task is to create a program to find the maximum subsequence sum in such a way that no two consecutive elements of the array.
Problem Description − We need to find the sum of subarray which has elements of the array but no two adjacent elements of the array can be taken into consideration.
Example
Let’s take an example to understand the problem,
Input
arr[] = {5, 2, 1, 9, 6}
Output
Explanation −
Subarray sum are : {5, 1, 6}, sum = 5 + 1 + 6 = 12 {2, 9}, sum = 2 + 9 = 11
Solution Approach
Here, we will have an alternate solution to the problem which is using a dynamic programming approach. In this approach, we will find subsequences satisfying the given condition and printing the maximum of it. We will create an array maxSumDP[n] that stores the maximum sub of the subsequence created. The element maxSumDP[i] stores the maximum sum of subsequences created by taking elements from index i to n-1. For this we can either consider the current element of the array arr[i] i.e. maxSumDP[i] = arr[i] + maxSumDP[i+2]. Or do not consider the current element of the array arr[i] i.e. maxSumDP[i] = maxSumDP[i+2].
Algorithm
Initialize −
maxSumDP[]
Step 2 −
initialize the values of maxSumDP[n−1] and maxSumDP[n−2]. maxSumDP[n−1] = arr[n−1] and maxSumDP[n−2] = max(arr[n−1], arr[n−2]).
Step 2 −
loop for i −> n−2 to 0
Step 1.2 −
initialize the value of maxSumDP[i], maxSumDP[i] = maximum of (arr[i] + maxSumDP[i + 2], maxSumDP[i + 1])
Step 3 −
Return maxSumDP[0] which is the maximum sum sequence sum.
Example
Program to illustrate the working of our solution,
#include <iostream> using namespace std; int retMaxVal(int a, int b){ if(a > b) return a; return b; } int calcMaxSum(int arr[], int n){ int maxSumDP[n]; maxSumDP[n−1] = arr[n−1]; maxSumDP[n−2] = max(arr[n−1], arr[n−2]); for (int i = n − 2; i >= 0; i−−) { maxSumDP[i] = retMaxVal(arr[i] + maxSumDP[i + 2], maxSumDP[i + 1]); } return maxSumDP[0]; } int main() { int arr[] = { 5, 2 , 1, 9, 6 }; int n = sizeof(arr) / sizeof(int); cout<<"The maximum subsequence sum in such a way that no two consecutive elements of the array is "<<calcMaxSum(arr, n); return 0; }
Output
The maximum subsequence sum in such a way that no two consecutive elements of the array is 14