Skip to content

Commit 7ebade2

Browse files
adding my solution to 1518
1 parent 34f95ad commit 7ebade2

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

problems/1518/jeremymanning.md

+36-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,45 @@
11
# [Problem 1518: Water Bottles](https://leetcode.com/problems/water-bottles)
22

33
## 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+
412

513
## 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`)
618

719
## Attempted solution(s)
820
```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
1134
```
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+
![Screenshot 2024-07-06 at 11 47 50 PM](https://github.com/ContextLab/leetcode-solutions/assets/9030494/66a9540c-5afc-4cd4-9652-6e8aa99ab59d)
44+
45+
Slow, but I'll take it-- solved!

0 commit comments

Comments
 (0)