Maximum product of a triplet ( subsequence of size 3 ) in 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 code
function maxProduct ( arr , n ) { if ( n < 3 ) return - 1 ; var maxA = Number . MIN_VALUE , maxB = Number . MIN_VALUE , maxC = Number . MIN_VALUE ; var minA = Number . MAX_VALUE , minB = Number . MAX_VALUE ; for ( 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 Math . max ( minA * minB * maxA , maxA * maxB * maxC ) ; } var arr = [ 1 , - 4 , 3 , - 6 , 7 , 0 ] ; var n = arr . length ; var max = maxProduct ( arr , n ) ; if ( max == - 1 ) document . write ( " " ) ; else document . write ( " " + max ) ;