28(May) Minimum cost to fill given weight in a bag

28. Minimum Cost to Fill Given Weight in a Bag

The problem can be found at the following link: Question Link

Problem Description

Given an array cost[] of positive integers of size n and an integer w, where cost[i] represents the cost of an i kg packet of oranges, the task is to find the minimum cost to buy exactly w kg of oranges. The cost array has a 1-based indexing. If buying exactly w kg of oranges is impossible, then return -1.

Note:

  1. cost[i] = -1 means that i kg packet of orange is unavailable.

  2. It may be assumed that there is an infinite supply of all available packet types.

Example:

Input:

n = 5
cost[] = {20, 10, 4, 50, 100}
w = 5

Output:

14

Explanation: Purchase the 2kg packet for 10 coins and the 3kg packet for 4 coins to buy 5kg of oranges for 14 coins.

My Approach

  1. Initialization:

    • Create a 2D vector memo of size (n + 1) x (w + 1) initialized to -1 to store the minimum cost to achieve a certain weight using available packets up to a certain index.

    • Define a helper function findMinCost that takes the current index, the cost array, the remaining weight, and the memoization table as parameters.

  2. Base Cases:

    • If the weight is 0, return 0 (no cost required for 0 weight).

    • If the index exceeds the length of the cost array or the weight is less than the current packet size, return INT_MAX (indicating infeasibility).

  3. Recursive Calculation:

    • If the current index cost is available and it does not exceed the remaining weight, consider including it and calculate the result recursively for the remaining weight.

    • Also, consider excluding the current index and moving to the next.

    • Store and return the minimum of these two choices in the memoization table.

  4. Return Result:

    • Call the helper function starting from index 0 and the full weight w.

    • If the result is INT_MAX, return -1, otherwise return the result.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n * w), as we compute the minimum cost for each possible combination of index and weight using memoization.

  • Expected Auxiliary Space Complexity: O(n * w), as we use a 2D vector of size (n + 1) x (w + 1) to store intermediate results.

Code

C++

Java

Python

Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


📍Visitor Count

Last updated