text: Minimum cost of purchasing at least X chocolates | C ++ program for the 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinCost ( pair < int , int > arr [ ] , int X , int n , int i = 0 ) { if ( X <= 0 ) return 0 ; if ( i >= n ) return INT_MAX ; int inc = findMinCost ( arr , X - arr [ i ] . first , n , i + 1 ) ; if ( inc != INT_MAX ) inc += arr [ i ] . second ; int exc = findMinCost ( arr , X , n , i + 1 ) ; return min ( inc , exc ) ; } int main ( ) { pair < int , int > arr [ ] = { { 4 , 3 } , { 3 , 2 } , { 2 , 4 } , { 1 , 3 } , { 4 , 2 } } ; int X = 7 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int ans = findMinCost ( arr , X , n ) ; if ( ans != INT_MAX ) cout << ans ; else cout << -1 ; return 0 ; }