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

## Input

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

## Output

Maximum litres of water: 3

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

## Input

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

## Output

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.

## Example

Live Demo

// CPP implementation of the above approach
#include<bits/stdc++.h>
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;
litrs=tmp>0?tmp:0;
mny-=litrs*gb;
// no. of plastic bottles
litrs+=mny/pb;
cout<<"Maximum Liters of water : "<<litrs<<endl;
}
// only plastic bottles
else
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 );
}

## Output

Maximum Liters of water: 14