Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum how many water bottles we can drink in Python
Suppose there are n number of full water bottles, and we can exchange m empty water bottles for one full water bottle. Drinking a full water bottle makes it an empty bottle. We have to find the maximum number of water bottles we can drink.
So, if the input is like n = 9, m = 3, then the output will be 13 because initially we have 9 bottles. After drinking all bottles, we get 9/3 = 3 full bottles from the empty ones. After drinking those 3, we have 3 empty bottles which gives us 1 more full bottle. So total: 9 + 3 + 1 = 13 bottles.
Algorithm
To solve this, we will follow these steps ?
x := n, s := 0, k := 0
-
while x >= m, do
k := x mod m
x := quotient of x / m
s := s + x
x := x + k
return n + s
Example
Let us see the following implementation to get better understanding ?
def solve(n, m):
x = n
s = 0
k = 0
while x >= m:
k = x % m
x = x // m
s = s + x
x = x + k
return n + s
n = 9
m = 3
print(solve(n, m))
13
How It Works
The algorithm works by simulating the exchange process:
x tracks current empty bottles
s accumulates bottles gained from exchanges
k stores remaining empty bottles after each exchange
def solve_with_steps(n, m):
x = n
s = 0
total_drunk = n
print(f"Initially: {n} bottles drunk")
while x >= m:
new_bottles = x // m
remaining_empty = x % m
s += new_bottles
total_drunk += new_bottles
x = new_bottles + remaining_empty
print(f"Exchange: {new_bottles} new bottles, {remaining_empty} empty left, total drunk: {total_drunk}")
return total_drunk
n = 15
m = 4
result = solve_with_steps(n, m)
print(f"Maximum bottles: {result}")
Initially: 15 bottles drunk Exchange: 3 new bottles, 3 empty left, total drunk: 18 Exchange: 1 new bottles, 2 empty left, total drunk: 19 Maximum bottles: 19
Conclusion
The solution uses a while loop to simulate the bottle exchange process until we have fewer empty bottles than required for exchange. The total bottles drunk equals initial bottles plus all bottles gained through exchanges.
