![]() |
VOOZH | about |
You are given a bag of size w kg and you are provided costs of packets different weights of oranges in array cost[], find the minimum total cost to buy exactly w kg oranges.
Examples:
Input : w = 5, cost[] = [20, 10, 4, 50, 100]
Output : 14
Explanation: We can choose two oranges to minimize cost. First orange of 2 Kg and cost 10. Second orange of 3 Kg and cost 4.Input : w = 5, cost[] = [1, 10, 4, 50, 100]
Output : 5
Explanation : We can choose five oranges of weight 1 kg.Input : w = 5, cost[] = [1, 2, 3, 4, 5]
Output : 5
Explanation : Costs of 1, 2, 3, 4 and 5 kg packets are 1, 2, 3, 4 and 5 Rs respectively. We choose packet of 5 kg having cost 5 for minimum cost to get 5 Kg oranges.Input : w = 5, cost[] = [-1, -1, 4, 5, -1 ]
Output : -1
Explanation: Packets of size 1, 2 and 5 kg are unavailable because they have cost -1. Cost of 3 kg packet is 4 Rs and of 4 kg is 5 Rs. Here we have only weights 3 and 4 so by using these two we can not make exactly W kg weight, therefore answer is -1.
Table of Content
This problem is can be reduced to Unbounded Knapsack. So in the cost array, we first ignore those packets which are not available i.e; cost is -1 and then traverse the cost array and create two array val[] for storing the cost of 'i' kg packet of orange and wt[] for storing weight of the corresponding packet. Suppose cost[i] = 50 so the weight of the packet will be i and the cost will be 50.
Below is the implementation of the above algorithm:
5
If we take a closer look at this problem, we may notice that this is a variation of Rod Cutting Problem. Instead of doing maximization, here we need to do minimization.
dp[i] : minimum cost to get exactly weight ii, try all packets with weights less than it.14