text: Minimum cost of purchasing at least X chocolates | 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 ; Given array and value of X ; Store the size of the array ; Print the answer
code: function findMinCost ( arr , X , n , i = 0 ) { if ( X <= 0 ) return 0 ; if ( i >= n ) return Number . MAX_SAFE_INTEGER ; let inc = findMinCost ( arr , X - arr [ i ] [ 0 ] , n , i + 1 ) ; if ( inc != Number . MAX_SAFE_INTEGER ) inc += arr [ i ] [ 1 ] ; let exc = findMinCost ( arr , X , n , i + 1 ) ; return Math . min ( inc , exc ) ; } let arr = [ [ 4 , 3 ] , [ 3 , 2 ] , [ 2 , 4 ] , [ 1 , 3 ] , [ 4 , 2 ] ] ; let X = 7 ; let n = arr . length ; let ans = findMinCost ( arr , X , n ) ; if ( ans != Number . MAX_SAFE_INTEGER ) document . write ( ans ) else document . write ( - 1 )