I start by drinking all the initial bottles, keeping track of empties. While I have enough empties to exchange for a full one, I perform the exchange, drink those, and update my empty count. I continue until I can no longer exchange.
class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
total = numBottles
empty = numBottles
while empty >= numExchange:
new_full = empty // numExchange
total += new_full
empty = empty % numExchange + new_full
return total- Time: O(log(numBottles)) (since bottles shrink with each exchange)
- Space: O(1)