#1518

Water Bottles

Easy
MathSimulationGreedy AlgorithmsSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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
  1. 1Step 1: Initialize totalDrunk with numBottles.
  2. 2Step 2: While numBottles is greater than or equal to numExchange, do the following:
  3. 3Step 3: Calculate how many new full bottles we can get (newBottles = numBottles // numExchange).
  4. 4Step 4: Update totalDrunk by adding newBottles, and update numBottles to reflect the new full bottles plus the remaining empty bottles.
  5. 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.