#3100

Water Bottles II

Medium
MathSimulationSimulationGreedy
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 efficiently calculates the total number of bottles drunk without simulating each step. It uses a loop to keep track of empty bottles and adjusts the numExchange dynamically.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize total_drunk to numBottles and empty_bottles to numBottles.
  2. 2Step 2: While empty_bottles is greater than or equal to numExchange, perform the following:
  3. 3Step 3: Calculate full_bottles from empty_bottles and update total_drunk.
  4. 4Step 4: Update empty_bottles for the next iteration.
  5. 5Step 5: Increase numExchange by 1.
solution.py9 lines
1def maxWaterBottles(numBottles, numExchange):
2    total_drunk = numBottles
3    empty_bottles = numBottles
4    while empty_bottles >= numExchange:
5        full_bottles = empty_bottles // numExchange
6        total_drunk += full_bottles
7        empty_bottles = empty_bottles % numExchange + full_bottles
8        numExchange += 1
9    return total_drunk

Complexity note: The complexity is O(n) because we only loop through the number of empty bottles, and each operation inside the loop is constant time.

  • 1Exchanging empty bottles increases the number of full bottles, allowing for more drinking.
  • 2The number of exchanges needed increases with each successful exchange, making it essential to track both full and empty bottles.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.