Problem
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.
Examples
Example 1:
|
|
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.
|
|
Example 2:
|
|
Solution
Method 2 - Iterative
As long as there are at least numExchange
bottles remaining, we can drink them and exchange the empty bottles for full ones.
Code
|
|
Complexity
- ⏰ Time complexity:
O(log n)
, wheren
is number of bottles - 🧺 Space complexity:
O(1)
Method 2 - Geometric Progression
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:
|
|
So, we can see that a
= 9, r
= 1/3,
|
|
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:
$$ \text{Total} = n + \left\lfloor \sum_{i=0}^{\infty} \left\lfloor \frac{n}{k} \right\rfloor \right\rfloor $$
To derive the total exchanges, realize that every additional bottle obtained through exchanges adds: $$ \frac{n-1}{k-1} $$
Simplified Geometric Series - Combining all, the total number of bottles you can drink simplifies to:
$$ \text{Total} = n + \frac{n-1}{k-1} $$
Code
|
|
Complexity
- ⏰ Time complexity:
O(1)
- 🧺 Space complexity:
O(1)