Skip to content

Commit 261cac6

Browse files
committed
feat: add LeetCode 1518 Water Bottles solution
- Implement simulation approach with O(log n) time complexity - Include alternative mathematical O(1) solution in comments - Add comprehensive problem explanation and examples - Addresses GitHub issue #22
1 parent 8d6f4a0 commit 261cac6

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

1518. Water Bottles.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public:
3+
int numWaterBottles(int numBottles, int numExchange) {
4+
int totalDrunk = numBottles;
5+
int emptyBottles = numBottles;
6+
7+
while (emptyBottles >= numExchange) {
8+
int newBottles = emptyBottles / numExchange;
9+
totalDrunk += newBottles;
10+
emptyBottles = emptyBottles % numExchange + newBottles;
11+
}
12+
13+
return totalDrunk;
14+
}
15+
};
16+
17+
/*
18+
Alternative Mathematical Solution (More Efficient):
19+
class Solution {
20+
public:
21+
int numWaterBottles(int numBottles, int numExchange) {
22+
// Mathematical formula: numBottles + (numBottles - 1) / (numExchange - 1)
23+
return numBottles + (numBottles - 1) / (numExchange - 1);
24+
}
25+
};
26+
27+
Problem Explanation:
28+
- You have numBottles full water bottles
29+
- After drinking, you get numBottles empty bottles
30+
- You can exchange numExchange empty bottles for 1 new full bottle
31+
- Find maximum bottles you can drink
32+
33+
Example: numBottles = 9, numExchange = 3
34+
- Drink 9 bottles → 9 empty bottles
35+
- Exchange 9 empty → 3 new bottles, 0 empty remaining
36+
- Drink 3 bottles → 3 empty bottles
37+
- Exchange 3 empty → 1 new bottle, 0 empty remaining
38+
- Drink 1 bottle → 1 empty bottle
39+
- Cannot exchange anymore (need 3 empty for 1 new)
40+
- Total drunk: 9 + 3 + 1 = 13
41+
42+
Time Complexity: O(log(numBottles)) - simulation approach
43+
O(1) - mathematical approach
44+
Space Complexity: O(1)
45+
*/

0 commit comments

Comments
 (0)