top of page

A team of explorers is visiting the Sahara desert. Due to the extreme heat, they need to stay hydrated and have brought n bottles of different sizes to carry water. After travelling a few kilometre...

The question is: A team of explorers is visiting the Sahara desert. Due to the extreme heat, they need to stay hydrated and have brought n bottles of different sizes to carry water. After travelling a few kilometres, they run out of water but luckily find a water source. This water source has only L litres of water available, which is less than the combined capacity of all their bottles. They need to fill L litres of water using the minimum number of bottles. Describe a greedy algorithm to help them fill L litres of water using the minimum number of bottles.


So, we have to minimize the number of water bottles. We know that each bottle is of a different size. We can do this by filling the largest bottle first and the smallest last. Let us design a greedy strategy to do this.


  1. Sort the Bottles: Sort the array of bottle capacities in descending order.

  2. Initialize Counters:

  • Set a counter for the number of bottles used to zero.

  • Set a variable for the total amount of water collected to zero.

  1. Select Bottles:

  • Iterate through the sorted list of bottle capacities.

  • For each bottle:

  • Add its capacity to the total amount of water collected.

  • Increment the counter for the number of bottles used.

  • If the total amount of water collected is greater than or equal to L litres, stop the iteration.

  1. Check and Output:

  • If the total amount of water collected is at least L litres, output the number of bottles used.

  • If it's not possible to collect L litres after using all the bottles, indicate that it is not possible.

62 views0 comments
logo

Crookshanks Academy is an online learning platform with free netflix styled courses.

Crookshanks Academy 2023 ©️ All Rights Reserved

This content is protected from right clicks.
bottom of page