# Maximum sum such that no two elements are adjacent 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 with the most efficient solution.

## Example

Live Demo

#include<stdio.h>
//calculating maximum sum
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;
}

## Output

110
Published on 27-Jul-2020 11:54:22