Skip to content
Related Articles

Related Articles

Improve Article
Minimum cost of purchasing at least X chocolates
  • Difficulty Level : Hard
  • Last Updated : 14 May, 2021

Given a positive integer X and an array arr[] consisting of N pairs, where each pair (A, B) represents a box, where A represents the number of chocolates and B represents the cost of the current box. The task is to find the minimum cost to buy at least X number of chocolates.

Examples:

Input: arr[] = {{4, 3}, {3, 2}, {2, 4}, {1, 3}, {4, 2}}, X = 7
Output: 4
Examples: Select the 2nd and the 5th box. Number of chocolates = 3 + 4 = 7.
Total cost = 2 + 2 = 4, which is the minimum cost to buy at least 7 chocolates.

Input: arr[] = {{10, 2}, {5, 3}}, X = 20
Output: -1
Examples: There exists no set of boxes which satisfies the given condition.

 

Naive Approach: The simplest approach is to use recursion, to consider all subsets of boxes and calculate the cost and number of chocolates of all subsets. From all such subsets, pick the subset having the minimum cost and at least X chocolates.
Optimal Sub-structure: To consider all subsets of items, there can be two cases for every box. 



  • Case 1: The item is included in the optimal subset. If the current box is included, then add the cost of this box and decrement X by the number of chocolates in the current box. And recur for the remaining X chocolates moving to the next index.
  • Case 2: The item is not included in the optimal set. If the current box is not included, then just recur for the remaining X chocolates moving to the next index.

Therefore, the minimum cost that can be obtained is the minimum of the above two cases. Handle the base case if X ≤ 0, return 0.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate minimum cost
// of buying least X chocolates
int findMinCost(pair<int, int> arr[],
                int X, int n, int i = 0)
{
    // Base Case
    if (X <= 0)
        return 0;
 
    if (i >= n)
        return INT_MAX;
 
    // Include the i-th box
    int inc = findMinCost(arr,
                          X - arr[i].first,
                          n, i + 1);
 
    if (inc != INT_MAX)
        inc += arr[i].second;
 
    // Exclude the i-th box
    int exc = findMinCost(arr, X, n, i + 1);
 
    // Return the minimum of
    // the above two cases
    return min(inc, exc);
}
 
// Driver Code
int main()
{
    // Given array and value of  X
    pair<int, int> arr[] = {
        { 4, 3 }, { 3, 2 },
        { 2, 4 }, { 1, 3 }, { 4, 2 }
    };
 
    int X = 7;
 
    // Store the size of the array
    int n = sizeof(arr) / sizeof(arr[0]);
 
    int ans = findMinCost(arr, X, n);
 
    // Print the answer
    if (ans != INT_MAX)
        cout << ans;
    else
        cout << -1;
 
    return 0;
}

Python3




# Python3 program for the above approach
 
# Function to calculate minimum cost
# of buying least X chocolates
def findMinCost(arr,X, n, i = 0):
   
    # Base Case
    if (X <= 0):
        return 0
 
    if (i >= n):
        return 10**8
 
    # Include the i-th box
    inc = findMinCost(arr,X - arr[i][0], n, i + 1)
 
    if (inc != 10**8):
        inc += arr[i][1]
 
    # Exclude the i-th box
    exc = findMinCost(arr, X, n, i + 1)
 
    # Return the minimum of
    # the above two cases
    return min(inc, exc)
 
# Driver Code
if __name__ == '__main__':
   
    # Given array and value of  X
    arr = [[ 4, 3 ], [ 3, 2 ],[ 2, 4 ], [ 1, 3 ], [ 4, 2 ]]
 
    X = 7
 
    # Store the size of the array
    n = len(arr)
    ans = findMinCost(arr, X, n)
 
    # Prthe answer
    if (ans != 10**8):
        print(ans)
    else:
        print(-1)
 
        # This code is contributed by mohit kumar 29.

C#




// C# program for the above approach
using System;
class GFG
{
   
    // Function to calculate minimum cost
    // of buying least X chocolates
    static int findMinCost(int[, ] arr, int X, int n,
                           int i = 0)
    {
       
        // Base Case
        if (X <= 0)
            return 0;
 
        if (i >= n)
            return Int32.MaxValue;
 
        // Include the i-th box
        int inc = findMinCost(arr, X - arr[i, 0], n, i + 1);
 
        if (inc != Int32.MaxValue)
            inc += arr[i, 1];
 
        // Exclude the i-th box
        int exc = findMinCost(arr, X, n, i + 1);
 
        // Return the minimum of
        // the above two cases
        return Math.Min(inc, exc);
    }
 
    // Driver Code
    public static void Main()
    {
       
        // Given array and value of  X
        int[, ] arr = {
            { 4, 3 }, { 3, 2 }, { 2, 4 }, { 1, 3 }, { 4, 2 }
        };
 
        int X = 7;
 
        // Store the size of the array
        int n = arr.GetLength(0);
 
        int ans = findMinCost(arr, X, n);
 
        // Print the answer
        if (ans != Int32.MaxValue)
            Console.Write(ans);
        else
            Console.Write(-1);
    }
}
 
// This code is contributed by ukasp.

Javascript




<script>
 
        // Javascript program for the above approach
 
        // Function to calculate minimum cost
        // of buying least X chocolates
        function findMinCost( arr, X, n,  i = 0)
        {
            // Base Case
            if (X <= 0)
                return 0;
 
            if (i >= n)
                return Number.MAX_SAFE_INTEGER;
 
            // Include the i-th box
            let inc = findMinCost(arr,
                X - arr[i][0],
                n, i + 1);
 
            if (inc != Number.MAX_SAFE_INTEGER)
                inc += arr[i][1];
 
            // Exclude the i-th box
            let exc = findMinCost(arr, X, n, i + 1);
 
            // Return the minimum of
            // the above two cases
            return Math.min(inc, exc);
        }
 
        // Driver Code
            // Given array and value of  X
            let arr = [
                [ 4, 3 ], [ 3, 2 ],
                [ 2, 4 ], [ 1, 3 ], [ 4, 2 ]
            ];
 
            let X = 7;
 
            // Store the size of the array
            let n = arr.length;
 
            let ans = findMinCost(arr, X, n);
 
            // Print the answer
            if (ans != Number.MAX_SAFE_INTEGER)
                document.write(ans)
            else
                document.write(-1)
 
        // This code is contributed by Hritik
         
</script>

 
 

Output: 
4

 

 

Time Complexity: O(2N)
Auxiliary Space: O(1)

 

Efficient Approach: To optimize the above approach, the idea is to use dynamic programming since the problem contains overlapping subproblems and optimal substructure property. The idea is to use memoization to solve the problem. Create a 2D array, dp[N][X] to store the results in the recursive calls. If a particular state is already computed, then return its result stored in the table in constant time.

 



Below is the implementation of the above approach:

 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to calculate minimum
// cost of buying at least X chocolates
int findMinCostUtil(pair<int, int> arr[],
                    int X, int n,
                    int** dp, int i = 0)
{
    // Base cases
    if (X <= 0)
        return 0;
 
    if (i >= n)
        return INT_MAX;
 
    // If the state is already computed,
    // return its result from the 2D array
    if (dp[i][X] != INT_MAX)
        return dp[i][X];
 
    // Include the i-th box
    int inc = findMinCostUtil(arr,
                              X - arr[i].first,
                              n, dp,
                              i + 1);
 
    if (inc != INT_MAX)
        inc += arr[i].second;
 
    // Exclude the i-th box
    int exc = findMinCostUtil(arr, X, n,
                              dp, i + 1);
 
    // Update the result of
    // the state in 2D array
    dp[i][X] = min(inc, exc);
 
    // Return the result
    return dp[i][X];
}
 
// Function to find the minimum
// cost to buy at least X chocolates
void findMinCost(pair<int, int> arr[], int X, int n)
{
    // Create a 2D array, dp[][]
    int** dp = new int*[n + 1];
 
 
    // Initialize entries with INT_MAX
    for (int i = 0; i <= n; i++) {
 
        dp[i] = new int[X + 1];
 
        for (int j = 0; j <= X; j++)
 
            // Update dp[i][j]
            dp[i][j] = INT_MAX;
    }
 
    // Stores the minimum cost required
    int ans = findMinCostUtil(arr, X, n, dp);
 
    // Print the answer
    if (ans != INT_MAX)
        cout << ans;
    else
        cout << -1;
}
 
// Driver Code
int main()
{
    // Given array and value of X
    pair<int, int> arr[] = {
        { 4, 3 }, { 3, 2 },
        { 2, 4 }, { 1, 3 }, { 4, 2 }
    };
    int X = 7;
 
    // Store the size of the array
    int n = sizeof(arr) / sizeof(arr[0]);
 
    findMinCost(arr, X, n);
 
    return 0;
}

 
 

Output: 
4

 

 

Time Complexity: O(N * X)
Auxiliary Space: O(N * X)

 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :