Maximum Sum Decreasing Subsequence in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of N integers. Our task is to find the Maximum Sum Decreasing Subsequence in C++.

Problem Description

We will find the maximum sum of elements from the array such that the subsequence is strictly decreasing.

Let’s take an example to understand the problem,

Input

arr[] = {3, 1, 6, 10, 5, 2, 9}

Output

17

Explanation

Decreasing subsequence with max sum is {10, 5, 2} = 10 + 5 + 2 = 17

Solution Approach

Here, we will use the dynamic programming approach to find the solution. Here, we will create a maxSum[] array which will store the maxSum till the index i. The follow formula is employed to find array values,

maxSum[i] = arr[i] + max(maxSum[0 … (*i-1)])

The maximum sum is given by the maximum element of the array maxSum[].

Example

Program to illustrate the working of our solution,

Live Demo

#include <iostream>
using namespace std;
int findMaxSumDecSubSeq(int arr[], int N){
int maximumSum = 0;
int maxSum[N];
for (int i = 0; i < N; i++)
maxSum[i] = arr[i];
for (int i = 1; i < N; i++)
for (int j = 0; j < i; j++)
if (arr[i] < arr[j] && maxSum[i] < maxSum[j] + arr[i])
maxSum[i] = maxSum[j] + arr[i];
for (int i = 0; i < N; i++)
if (maximumSum < maxSum[i])
maximumSum = maxSum[i];
return maximumSum;
}
int main(){
int arr[] = { 5, 4, 100, 3, 2, 101, 1 };
int N= sizeof(arr) / sizeof(arr[0]);
cout<<"The maximum sum of decreasing subsequence is "<<findMaxSumDecSubSeq(arr, N);
return 0;
}

Output

The maximum sum of decreasing subsequence is 106
Updated on 15-Oct-2020 13:51:08

Advertisements