Maximum product of a triplet ( subsequence of size 3 ) in array | A O ( n ) Python3 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 Code
import sys NEW_LINE def maxProduct ( arr , n ) : NEW_LINE INDENT if ( n < 3 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT maxA = - sys . maxsize - 1 NEW_LINE maxB = - sys . maxsize - 1 NEW_LINE maxC = - sys . maxsize - 1 NEW_LINE minA = sys . maxsize NEW_LINE minB = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > maxA ) : NEW_LINE INDENT maxC = maxB NEW_LINE maxB = maxA NEW_LINE maxA = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > maxB ) : NEW_LINE INDENT maxC = maxB NEW_LINE maxB = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > maxC ) : NEW_LINE INDENT maxC = arr [ i ] NEW_LINE DEDENT if ( arr [ i ] < minA ) : NEW_LINE INDENT minB = minA NEW_LINE minA = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < minB ) : NEW_LINE INDENT minB = arr [ i ] NEW_LINE DEDENT DEDENT return max ( minA * minB * maxA , maxA * maxB * maxC ) NEW_LINE DEDENT arr = [ 1 , - 4 , 3 , - 6 , 7 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE Max = maxProduct ( arr , n ) NEW_LINE if ( Max == - 1 ) : NEW_LINE INDENT print ( " No ▁ Triplet ▁ Exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Maximum ▁ product ▁ is " , Max ) NEW_LINE DEDENT