Maximum litres of water that can be bought with N Rupees in C++

C++Server Side ProgrammingProgramming

We are given N rupees. The goal is to buy maximum water possible with the money where the rates of water bottles are as follows −

  • Plastic Bottles: A Rupees for 1 litre
  • Glass Bottles: B Rupees for 1 litre
  • Glass Bottles: B Rupees for 1 litre

Now the original cost of glass bottles becomes B-E rupees. After returning.

If the cost of plastic bottles is still less than B-E, then only buy plastic bottles. Else buy N-E/B-E glass bottles and spend rest on plastic bottles.


N = 6, A = 5, B = 4, E = 3;


Maximum litres of water: 3

Explanation − B-E=1, 1<A N-E=3, for 3 rupees we bought 3 1 litre glass bottles


N = 10, A = 5, B = 10, E = 3;


Maximum litres of water: 2

Explanation − B-E=7, 7>A n/a= 10/5 = 2 plastic bottles can be purchased

Approach used in the below program is as follows

  • Integers money, bottle, gbottle, and gempty are used for rates and amount of money we have.

  • Function maxWater(int mny,int pb,int gb,int ge) takes all values as parameters and prints the amount of water that can be purchased.

  • Variable litrs is used to store the calculated amount of water in litres.

  • We pass pb as a new value of glass bottle(original value-return value).

  • If passed gb value is less than pb value, then purchase (mny-ge)/gb glass bottles.

  • Subtract this amount to calculate left-over money, mny-=ltrs*gb

  • Now plastic bottles that can be purchased is mny/pb.

  • If the passed pb value is more than pb value then only purchase mny/pb plastic bottles.

  • Print results in both cases as no. of bottles is no. of litres of water. Each bottle has 1 litre capacity.


 Live Demo

// CPP implementation of the above approach
using namespace std;
void maxWater(int mny,int pb,int gb,int ge){
   int litrs;
   // if buying glass bottles is profitable
   if (gb < pb){
      // no. of glass bottles
      int tmp=mny-ge/gb;
      // no. of plastic bottles
      cout<<"Maximum Liters of water : "<<litrs<<endl;
   // only plastic bottles
      cout<<"Maximum Liters of water only Plastic bottles: "<<(mny /pb)<<endl;
int main(){
   int money = 20, pbottle=5, gbottle=10, gempty = 8;
   gbottle=gbottle-gempty; //new cost of glass botlles
   maxWater( money,pbottle,gbottle,gempty );


Maximum Liters of water: 14
Updated on 03-Aug-2020 09:43:21