# You have a bag that can hold 100kg of fruit. You are in a shop that...

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).

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:

1. Begin
2. sort the weighing in the non-increasing order
3. call this array as fruit array
4. for i= 0 to n-1 // Where n is the number of fruits
5. numberOfFruits += bagWeight/fruit[i]
6. bagWeight= bagWeight%fruit[i];
7. end
8. end

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

#### Earn Coin

Coins can be redeemed for fabulous gifts.