Maximum sum such that no two elements are adjacent 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

To solve the problem, we will simply loop over all elements of the array and maintain two sums. sumVar1 and sumVar2, sumVar1 will include sum with the current element and sumVar2 will include sum without current element.

With every iteration, we will update the sumVar2 as max(sumVar1, sumVar2). And then update the sumVar1. At the end of the loop, sumVar2 will give the required sum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include<iostream>
using namespace std;
int findmaximum(int a, int b){
   if(a > b)
      return a;
      return b;
}
int findMaxSumWOAdjecent(int arr[], int N){
   int maxSum1 = arr[0];
   int maxSum2 = 0;
   int temp;
   for (int i = 1; i < N; i++) {
      temp = findmaximum(maxSum1, maxSum2);
      maxSum1 = maxSum2 + arr[i];
      maxSum2 = temp;
   }
   return (findmaximum(maxSum1, maxSum2));
}
int main(){
   int arr[] = {5, 1, 3, 7, 9, 2, 5};
   int N = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum sum such that no two elements are adjacent is "<<findMaxSumWOAdjecent(arr, N);
   return 0;
}

Output

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

Updated on: 15-Oct-2020

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements