Water Bottles II - Problem

You are given two integers numBottles and numExchange.

numBottles represents the number of full water bottles that you initially have. In one operation, you can perform one of the following operations:

  • Drink any number of full water bottles turning them into empty bottles.
  • Exchange numExchange empty bottles with one full water bottle. Then, increase numExchange by one.

Note: You cannot exchange multiple batches of empty bottles for the same value of numExchange. For example, if numBottles == 3 and numExchange == 1, you cannot exchange 3 empty water bottles for 3 full bottles.

Return the maximum number of water bottles you can drink.

Input & Output

Example 1 — Basic Case
$ Input: numBottles = 13, numExchange = 6
Output: 15
💡 Note: Drink 13 bottles → 13 empties. Exchange 6 empties for 1 new bottle (cost becomes 7), leaving 7+1=8 empties. Drink 1 bottle → 8 empties. Exchange 7 empties for 1 new bottle (cost becomes 8), leaving 1+1=2 empties. Drink 1 bottle → 2 empties. Cannot exchange anymore (need 8, have 2). Total: 13+1+1=15
Example 2 — Higher Exchange Cost
$ Input: numBottles = 10, numExchange = 3
Output: 13
💡 Note: Drink 10 → 10 empties. Exchange 9 for 3 (cost=3), 1 empty left + 3 new = 4 empties total. Drink 3 → 7 empties. Exchange 4 for 1 (cost=4), 3 left + 1 new = 4 empties. Drink 1 → 5 empties. Exchange 5 for 1 (cost=5), 0 left + 1 new = 1 empty. Drink 1 → 1 empty. Total: 10+3+1+1=15
Example 3 — No Exchanges Possible
$ Input: numBottles = 2, numExchange = 4
Output: 2
💡 Note: Drink 2 bottles → 2 empties. Cannot exchange (need 4, have 2). Total: 2

Constraints

  • 1 ≤ numBottles ≤ 100
  • 1 ≤ numExchange ≤ 100

Visualization

Tap to expand
Water Bottles II - Mathematical Approach INPUT Initial Full Bottles (13) Exchange Rate 6 empty = 1 full numBottles 13 numExchange 6 Start with 13 bottles ALGORITHM STEPS 1 Initialize drunk = 13, empty = 13 2 Loop: Exchange While empty >= exchange Round | Empty | Exch | New | Drunk 1 | 13 | 6 | 1 | 14 2 | 8 | 7 | 1 | 15 3 | 2 | 8 | - | STOP 2 < 8: Cannot exchange more 3 Update Exchange numExchange++ after each 4 Return Total Return drunk count Greedy: always exchange FINAL RESULT Bottles Consumed 13 initial + 2 exchanged Breakdown: Initial drunk: 13 From exchange 1: 1 From exchange 2: 1 OUTPUT 15 Maximum bottles: 15 Key Insight: The exchange rate increases after each exchange, making future exchanges harder. Greedy approach works: always exchange when possible since waiting never helps. Time: O(sqrt(n)) | Space: O(1) - Exchange rate grows, limiting iterations. TutorialsPoint - Water Bottles II | Mathematical Approach
Asked in
Google 15 Amazon 12
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen