#1518
Water Bottles
EasyMathSimulationGreedy AlgorithmsSimulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages a mathematical approach to avoid unnecessary iterations. We can directly calculate the total number of bottles drunk by considering the number of exchanges possible in a more efficient way.
⚙️
Algorithm
5 steps- 1Step 1: Initialize totalDrunk with numBottles.
- 2Step 2: While numBottles is greater than or equal to numExchange, do the following:
- 3Step 3: Calculate how many new full bottles we can get (newBottles = numBottles // numExchange).
- 4Step 4: Update totalDrunk by adding newBottles, and update numBottles to reflect the new full bottles plus the remaining empty bottles.
- 5Step 5: Return totalDrunk after exiting the loop.
solution.py7 lines
1def numWaterBottles(numBottles, numExchange):
2 totalDrunk = numBottles
3 while numBottles >= numExchange:
4 newBottles = numBottles // numExchange
5 totalDrunk += newBottles
6 numBottles = newBottles + (numBottles % numExchange)
7 return totalDrunkℹ
Complexity note: The complexity remains O(n) as we still iterate based on the number of exchanges, but we avoid unnecessary calculations by directly updating the counts.
- 1The number of full bottles you can drink is directly related to how many empty bottles you can exchange.
- 2Each exchange allows you to drink more water, so maximizing exchanges is key.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.