There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.
Input: numBottles =9, numExchange =3Output: 13Explanation: You can exchange 3 empty bottles to get 1 full water bottle.Number of water bottles you can drink:9+3+1=13.
Lets assume ● is filled bottle, and ○ is empty bottle. Lets denote D for drink and X for exchange, then this is how it will work.
Input: numBottles =15, numExchange =4Output: 19Explanation: You can exchange 4 empty bottles to get 1 full water bottle.Number of water bottles you can drink:15+3+1=19.
We know that in Geometric Progression, when the progression is converging, then the formula is:
$$
S_{\infty} = \frac{a}{1-r}
$$
For eg. when r = 0.5 = 1/2, this is GP is converging.
These are the terms of GP for eg. 1:
1
2
3
t0 =9t1 =3t2 =1
So, we can see that a = 9, r = 1/3,
1
S = a /(1- r)=9/(1-1/3)=9/2/3=9*3/2=27/2=13
Note, answer is not 13.5, but 13, as we want 1 complete bottle, not half empty bottles.
So, this example worked, but we need to make sure we do integer division. So, lets derive the formula. Let n be initial bottles given, and k be number of bottles we exchange to get 1 full bottle.
First exchange:
$$
\left\lfloor \frac{n}{k} \right\rfloor
$$
Remaining Empty Bottles:
$$
n - \left( k \cdot \left\lfloor \frac{n}{k} \right\rfloor \right)
$$
Number of Full Bottles After Each Exchange:
$$
\sum_{i=0}^{\infty} \left\lfloor \frac{n_i}{k} \right\rfloor
$$
The total number of bottles you can drink is the sum of the initial bottles and the total number of full bottles obtained through exchanges. To simplify this calculation, we use the formula: