Minimum possible sum of prices of a Triplet from the given Array | Java Program to implement the above approach ; Function to minimize the sum of price by taking a triplet ; Initialize a dp [ ] array ; 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 java . util . * ; import java . io . * ; public class Main { public static long minSum ( int n , int num [ ] , int price [ ] ) { long dp [ ] = new long [ n ] ; Arrays . fill ( dp , Integer . MAX_VALUE ) ; long ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( num [ j ] > num [ i ] ) { dp [ j ] = ( long ) Math . min ( ( long ) dp [ j ] , ( long ) price [ i ] + ( long ) price [ j ] ) ; ans = Math . min ( ans , ( long ) dp [ i ] + ( long ) price [ j ] ) ; } } } return ans != Integer . MAX_VALUE ? ans : - 1 ; } public static void main ( String [ ] args ) { int num [ ] = { 2 , 4 , 6 , 7 , 8 } ; int price [ ] = { 10 , 20 , 100 , 20 , 40 } ; int n = price . length ; System . out . println ( minSum ( n , num , price ) ) ; } }