Minimum possible sum of prices of a Triplet from the given Array | Python3 program to implement the above approach ; Function to minimize the sum of price by taking a triplet ; Initialize a dp [ ] list ; Stores the final result ; Iterate for all values till N ; Check if num [ j ] > num [ i ] ; Update dp [ j ] if it is greater than stored value ; Update the minimum sum as ans ; If there is no minimum sum exist then print - 1 else print the ans ; Driver code
import sys ; NEW_LINE def minSum ( n , num , price ) : NEW_LINE INDENT dp = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = sys . maxsize NEW_LINE DEDENT ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( num [ j ] > num [ i ] ) : NEW_LINE INDENT dp [ j ] = min ( dp [ j ] , price [ i ] + price [ j ] ) NEW_LINE ans = min ( ans , dp [ i ] + price [ j ] ) NEW_LINE DEDENT DEDENT DEDENT if ans is not sys . maxsize : NEW_LINE INDENT return ans NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = [ 2 , 4 , 6 , 7 , 8 ] NEW_LINE price = [ 10 , 20 , 100 , 20 , 40 ] NEW_LINE n = len ( price ) NEW_LINE print ( minSum ( n , num , price ) ) NEW_LINE DEDENT