text: Minimum cost of purchasing at least X chocolates | Java program for above approach ; Function to calculate minimum cost of buying least X chocolates ; Base Case ; Include the i - th box ; Exclude the i - th box ; Return the minimum of the above two cases ; Driver Code ; Given array and value of X ; Store the size of the array ; Print the answer
code: class GFG { static int findMinCost ( int [ ] [ ] arr , int X , int n , int i ) { if ( X <= 0 ) return 0 ; if ( i >= n ) return Integer . MAX_VALUE ; int inc = findMinCost ( arr , X - arr [ i ] [ 0 ] , n , i + 1 ) ; if ( inc != Integer . MAX_VALUE ) inc += arr [ i ] [ 1 ] ; int exc = findMinCost ( arr , X , n , i + 1 ) ; return Math . min ( inc , exc ) ; } public static void main ( String [ ] args ) { int [ ] [ ] arr = { { 4 , 3 } , { 3 , 2 } , { 2 , 4 } , { 1 , 3 } , { 4 , 2 } } ; int X = 7 ; int n = arr . length ; int ans = findMinCost ( arr , X , n , 0 ) ; if ( ans != Integer . MAX_VALUE ) System . out . println ( ans ) ; else System . out . println ( - 1 ) ; } }