# Maximum subsequence sum such that no three are consecutive in C++ Program

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this problem, we are given an array arr[] consisting of n positive integers. Our task is to create a program to find the maximum subsequence sum such that no three are consecutive.

Problem Description − Here, we need to find the sum of sequences created from the array such that there are no three consecutive elements.

Consecutive elements of an array are those elements that have followed the same order of index.

arr, arr, arr, …

Let’s take an example to understand the problem,

## Input

arr[] = {5, 9, 12, 15}

## Output

32

## Explanation

Sum = 5 + 12 + 15 = 32

## Solution Approach

A simple solution to the problem is by creating an auxiliary array to store the sum until the current index. And then find the sum and check the sum till the index by checking for consecutive sums.

For the first two sum values,
sumVal = arr
sumVal = arr + arr

Then the third value to be considered cannot be directly considered. And for considering the sum, we will check for the conditions with the current three,If considering arr[i], increases the sum value, exclude arr[i−1] or arr[i−2].Else do not consider arr[i], the sum remains the same.

sum[i] = max(sum[i−3] + arr[i−1] + arr[i], sum[i−2] + arr[i], sum[i−1])

## Example

Program to show the implementation of our solution,

Live Demo

#include <iostream>
using namespace std;
int findMaxSubSeqSum(int arr[], int n) {
int maxSumArr[n];
maxSumArr = arr;
maxSumArr = arr + arr;
maxSumArr = max(maxSumArr, max(arr + arr, arr +
arr));
for (int i = 3; i < n; i++){
int sum1 = maxSumArr[i − 2] + arr[i];
int sum2 = arr[i] + arr[i − 1] + maxSumArr[i − 3];
maxSumArr[i] = max(max(maxSumArr[i − 1], sum1), sum2);
}
return maxSumArr[n − 1];
}
int main() {
int arr[] = { 5, 9, 12, 15 };
int n = sizeof(arr) / sizeof(arr);
cout<<"The maximum subsequence sum such that no three are
consecutive is "<<findMaxSubSeqSum(arr, n);
return 0;
}

## Output

The maximum subsequence sum such that no three are consecutive is 32