Advertisement
1518. Water Bottles
UnknownView on LeetCode
Time: O(log n)
Space: O(1)
Approach
Simulate; repeatedly exchange full bottles for new ones, tracking the total drunk.
1518.cs
C#
// Approach: Simulate; repeatedly exchange full bottles for new ones, tracking the total drunk.
// Time: O(log n) Space: O(1)
public class Solution
{
public int NumWaterBottles(int numBottles, int numExchange)
{
int ans = numBottles;
while (numBottles >= numExchange)
{
numBottles -= numExchange;
ans++;
numBottles += 1;
}
return ans;
}
}1518.py
Python
class Solution(object):
def numWaterBottles(self, numBottles, numExchange):
"""
:type numBottles: int
:type numExchange: int
:rtype: int
"""
ans = numBottles
while numBottles >= numExchange:
numBottles -= numExchange
ans += 1
numBottles += 1
return ans
Advertisement
Was this solution helpful?