|
| 1 | +# [1518. Water Bottles](https://leetcode.com/problems/water-bottles/?envType=daily-question&envId=2025-10-02) |
| 2 | + |
| 3 | +## Question Description |
| 4 | +There are numBottles water bottles that are initially full of water. |
| 5 | +You can exchange numExchange empty water bottles from the market with one full water bottle. |
| 6 | + |
| 7 | +The operation of drinking a full water bottle turns it into an empty bottle. |
| 8 | + |
| 9 | +Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink. |
| 10 | + |
| 11 | +--- |
| 12 | + |
| 13 | +## Constraints |
| 14 | +- 1 <= numBottles <= 100 |
| 15 | +- 2 <= numExchange <= 100 |
| 16 | + |
| 17 | +--- |
| 18 | + |
| 19 | +## Approach |
| 20 | +We simulate the process step by step: |
| 21 | +1. Drink all current bottles and increase the total count. |
| 22 | +2. Track how many empty bottles are collected. |
| 23 | +3. If empty bottles are enough for an exchange, convert them into new full bottles. |
| 24 | +4. Continue until you cannot exchange anymore. |
| 25 | + |
| 26 | +This works because each exchange is independent and only depends on the count of empty bottles at each step. |
| 27 | + |
| 28 | +--- |
| 29 | + |
| 30 | +## Dry Run |
| 31 | +Example Input: numBottles = 9, numExchange = 3 |
| 32 | + |
| 33 | +Step-by-step execution: |
| 34 | +- Start: count = 0, empty = 0, numBottles = 9 |
| 35 | +- Drink 9 bottles → count = 9, empty = 9 |
| 36 | +- Exchange 9/3 = 3 → numBottles = 3, empty = 0 |
| 37 | +- Drink 3 bottles → count = 12, empty = 3 |
| 38 | +- Exchange 3/3 = 1 → numBottles = 1, empty = 0 |
| 39 | +- Drink 1 bottle → count = 13, empty = 1 |
| 40 | +- Not enough bottles to exchange → Stop |
| 41 | + |
| 42 | +Final Answer = 13 |
| 43 | + |
| 44 | +--- |
| 45 | + |
| 46 | +## Solution |
| 47 | +```java |
| 48 | +class Solution { |
| 49 | + public int numWaterBottles(int numBottles, int numExchange) { |
| 50 | + int count = 0; |
| 51 | + int empty = 0; |
| 52 | + while (numBottles > 0) { |
| 53 | + count += numBottles; |
| 54 | + empty += numBottles; |
| 55 | + |
| 56 | + numBottles = empty / numExchange; |
| 57 | + empty = empty % numExchange; |
| 58 | + } |
| 59 | + return count; |
| 60 | + } |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +--- |
| 65 | + |
| 66 | +## Time and Space Complexity |
| 67 | +- **Time Complexity:** O(numBottles) in the worst case, as we simulate exchanges until bottles run out. |
| 68 | +- **Space Complexity:** O(1), using only a few variables. |
0 commit comments