|
1 | 1 | # [Problem 1518: Water Bottles](https://leetcode.com/problems/water-bottles)
|
2 | 2 |
|
3 | 3 | ## Initial thoughts (stream-of-consciousness)
|
| 4 | +- There's almost certainly an analytic solution to this problem-- something like (number of bottles) + (log (base exchange rate) number of bottles) + 1...but probably not *quite* that simple |
| 5 | +- The naive solution would be to do something like: |
| 6 | + - keep a running total of the number of bottles that have been drunk |
| 7 | + - then, until there are fewer than `numExchange` bottles left: |
| 8 | + - exchange as many bottles as possible and add that to the total |
| 9 | + - update the number of remaining bottles |
| 10 | +- If `numExchange` was 1, we'd get an infinite loop, but it looks like this isn't allowed (`2 <= numExchange <= 100`) |
| 11 | + |
4 | 12 |
|
5 | 13 | ## Refining the problem, round 2 thoughts
|
| 14 | +- I'll start by implementing the naive solution. Given the problem specification (maximum `numBottles` is 100, minimum `numExchange` is 2), I don't think we'll run out of compute time... |
| 15 | +- Updating the number of remaining bottles should work as follows: |
| 16 | + - Exchange whatever we can. The number of bottles now in our collection is `availableBottles // numExchange` |
| 17 | + - Also track what's left over (`availableBottles % numExchange`) |
6 | 18 |
|
7 | 19 | ## Attempted solution(s)
|
8 | 20 | ```python
|
9 |
| -class Solution: # paste your code here! |
10 |
| - ... |
| 21 | +class Solution: |
| 22 | + def numWaterBottles(self, numBottles: int, numExchange: int) -> int: |
| 23 | + drinkableTotal = numBottles |
| 24 | + bottlesAvailable = numBottles |
| 25 | + |
| 26 | + while bottlesAvailable >= numExchange: |
| 27 | + nextExchange = bottlesAvailable // numExchange |
| 28 | + drinkableTotal += nextExchange |
| 29 | + |
| 30 | + bottlesAvailable %= numExchange |
| 31 | + bottlesAvailable += nextExchange |
| 32 | + |
| 33 | + return drinkableTotal |
11 | 34 | ```
|
| 35 | +- All given test cases pass |
| 36 | +- Other test cases: |
| 37 | + - `numBottles = 100, numExchange = 2`: passes |
| 38 | + - `numBottles = 100, numExchange = 3`: passes |
| 39 | + - `numBottles = 100, numExchange = 4`: passes |
| 40 | + - `numBottles = 48, numExchange = 7`: passes |
| 41 | +- Seems ok...submitting... |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +Slow, but I'll take it-- solved! |
0 commit comments