Sponsored
Sponsored
This approach uses a simple iterative simulation to solve the problem. We keep track of the current number of full bottles and empty bottles. We repeatedly drink a full bottle and calculate how many empty bottles we have. If the number of empty bottles is enough to exchange for a new full bottle, we perform the exchange and continue the loop. This process is repeated until no more exchanges can be made.
Time Complexity: O(numBottles).
Space Complexity: O(1).
1public class WaterBottles {
2 public static int numWaterBottles(int numBottles, int numExchange) {
3 int totalDrank = numBottles;
4 int emptyBottles = numBottles;
5 while (emptyBottles >= numExchange) {
6 int newBottles = emptyBottles / numExchange;
7 totalDrank += newBottles;
8 emptyBottles = emptyBottles % numExchange + newBottles;
9 }
10 return totalDrank;
11 }
12
13 public static void main(String[] args) {
14 System.out.println(numWaterBottles(9, 3));
15 }
16}
This Java solution uses a while loop to simulate the drinking and exchanging process, continuously updating the count of total drinks and empty bottles available for exchange.
This approach leverages a mathematical understanding of the problem. Instead of simulating every exchange, you can calculate how many overall bottles you'll get by using a formula. This involves understanding the number of bottles resulting from continuous exchanges until no more can be made.
Time Complexity: O(log(numBottles)).
Space Complexity: O(1).
1using System;
2
class WaterBottles {
public static int NumWaterBottles(int numBottles, int numExchange) {
int total = numBottles;
while (numBottles >= numExchange) {
int newBottles = numBottles / numExchange;
total += newBottles;
numBottles = numBottles % numExchange + newBottles;
}
return total;
}
static void Main() {
Console.WriteLine(NumWaterBottles(15, 4));
}
}
The C# solution leverages a while loop to update total bottles with new ones obtained from exchanges, offering a compact calculation.