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).
1#
In this C solution, a while loop is used to calculate the total number of bottles drunk by updating the current bottles with the new one obtained from the exchange.