Maximum product of a triplet ( subsequence of size 3 ) in array | A O ( n ) C ++ program to find maximum product pair in an array . ; Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; Initialize Maximum , second maximum and third maximum element ; Initialize Minimum and second minimum element ; Update Maximum , second maximum and third maximum element ; Update second maximum and third maximum element ; Update third maximum element ; Update Minimum and second minimum element ; Update second minimum element ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProduct ( int arr [ ] , int n ) { if ( n < 3 ) return -1 ; int maxA = INT_MIN , maxB = INT_MIN , maxC = INT_MIN ; int minA = INT_MAX , minB = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > maxA ) { maxC = maxB ; maxB = maxA ; maxA = arr [ i ] ; } else if ( arr [ i ] > maxB ) { maxC = maxB ; maxB = arr [ i ] ; } else if ( arr [ i ] > maxC ) maxC = arr [ i ] ; if ( arr [ i ] < minA ) { minB = minA ; minA = arr [ i ] ; } else if ( arr [ i ] < minB ) minB = arr [ i ] ; } return max ( minA * minB * maxA , maxA * maxB * maxC ) ; } int main ( ) { int arr [ ] = { 1 , -4 , 3 , -6 , 7 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max = maxProduct ( arr , n ) ; if ( max == -1 ) cout << " No ▁ Triplet ▁ Exists " ; else cout << " Maximum ▁ product ▁ is ▁ " << max ; return 0 ; }