Maximum product of an increasing subsequence in C++ Program


In this problem, we are given an array arr[] of size n. Our task is to find the maximum product of an increasing subsequence.

Problem Description − We need to find the maximum product of increasing subsequence of any size possible from the elements of the array.

Let’s take an example to understand the problem,

Input

arr[] = {5, 4, 6, 8, 7, 9}

Output

2160

Explanation

All Increasing subsequence:
{5,6,8,9}. Prod = 2160
{5,6,7,9}. Prod = 1890
Here, we have considered only max size subsequence.

Solution Approach

A simple solution to the problem is by using a dynamic programming approach. For this, we will store the maximum product increasing subsequence till the given element of the array and then store in an array.

Algorithm

Initialise

prod[] with elements of arr[].
maxProd = −1000

Step 1

Loop for i −> 0 to n−1

Step 1.1

Loop for i −> 0 to i

Step 1.1.1

Check if the current element creates an increasing
subsequence i.e. arr[i]>arr[j] and arr[i]*prod[j]> prod[i] −>
prod[i] = prod[j]*arr[i]

Step 2

find the maximum element of the array. Following steps 3 and 4.

Step 3

Loop form i −> 0 to n−1

Step 4

if(prod[i] > maxProd) −> maxPord = prod[i]

Step 5

return maxProd.

Example

Program to show the implementation of our solution,

 Live Demo

#include <iostream>
using namespace std;
long calcMaxProdSubSeq(long arr[], int n) {
   long maxProdSubSeq[n];
   for (int i = 0; i < n; i++)
   maxProdSubSeq[i] = arr[i];
   for (int i = 1; i < n; i++)
   for (int j = 0; j < i; j++)
   if (arr[i] > arr[j] && maxProdSubSeq[i] <
      (maxProdSubSeq[j] * arr[i]))
   maxProdSubSeq[i] = maxProdSubSeq[j] * arr[i];
   long maxProd = −1000 ;
   for(int i = 0; i < n; i++){
      if(maxProd < maxProdSubSeq[i])
         maxProd = maxProdSubSeq[i];
   }
   return maxProd;
}
int main() {
   long arr[] = {5, 4, 6, 8, 7, 9};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum product of an increasing subsequence is "<<calcMaxProdSubSeq(arr, n);
   return 0;
}

Output

The maximum product of an increasing subsequence is 2160

Updated on: 09-Dec-2020

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements