Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Maximum product of an increasing subsequence of size 3 in C++
In this tutorial, we will be discussing a program to find maximum product of an increasing subsequence of size 3.
For this we will be provided with an array of positive integers. Our task is to find a subsequence of three elements with the maximum product.
Example
#include<bits/stdc++.h>
using namespace std;
//returning maximum product of subsequence
long long int maxProduct(int arr[] , int n) {
int smaller[n];
smaller[0] = -1 ;
set<int>S ;
for (int i = 0; i < n ; i++) {
auto j = S.insert(arr[i]);
auto itc = j.first;
--itc;
if (itc != S.end())
smaller[i] = *itc;
else
smaller[i] = -1;
}
long long int result = INT_MIN;
int max_right = arr[n-1];
for (int i=n-2 ; i >= 1; i--) {
if (arr[i] > max_right)
max_right = arr[i];
else if (smaller[i] != -1)
result = max(smaller[i] * arr[i] * max_right, result);
}
return result;
}
int main() {
int arr[] = {10, 11, 9, 5, 6, 1, 20};
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxProduct(arr, n) << endl;
return 0;
}
Output
2200
Advertisements
