You have a bag that can hold 100kg of fruit. You are in a shop that sells (an un
ID: 3598389 • Letter: Y
Question
You have a bag that can hold 100kg of fruit. You are in a shop that sells (an unlimited supply of) pumpkins, watermelons, and squash, weighing 10, 2, and 1kg each, respectively. Give a greedy algorithm to fill your bag with the smallest number of fruits/vegetables (eg, buying a watermelon is preferable to buying two squash, etc). The total weight has to be exactly 100kg. Argue that this will return you the optimal solution. Argue that, given this fruit/vegetable collection, you can completely fill a bag of any weight capacity (ie, you can realize any weight, not just 100kg).
Explanation / Answer
Solution:
As given in the problem, we have an unlimited amount of supply.
This means that we can take as many weighted items we can and then rest of the items with smaller weight in the decreasing order in order to produce the minimum number of fruits.
the algorithm is given below:
The given algorithm is first filling all the most weighted fruits/vegetables in the bag then the next weighted item is placed in the bag, the given approach is a greedy approach and it will always produce an optimal solution.
Suppose the bag weight is 113 then our algorithm will return
113/10= 11
numberOfFruits = 11
then
113%10= 3
numberOfFruits = 11 + (3/2)= 11 + 1= 12
then 1 is remining
which means
numberOfFruits = 12 + 1= 13
Please, please upvote and ask your doubts in the comments.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.