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).
1using System;
2
3class WaterBottles {
4 public static int NumWaterBottles(int numBottles, int numExchange) {
5 int totalDrank = numBottles;
6 int emptyBottles = numBottles;
7 while (emptyBottles >= numExchange) {
8 int newBottles = emptyBottles / numExchange;
9 totalDrank += newBottles;
10 emptyBottles = emptyBottles % numExchange + newBottles;
11 }
12 return totalDrank;
13 }
14
15 public static void Main() {
16 Console.WriteLine(NumWaterBottles(9, 3));
17 }
18}
This C# solution provides a simulation of the exchange process by maintaining and updating the total and empty bottles in a while loop.
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#include <iostream>
2
int numWaterBottles(int numBottles, int numExchange) {
int total = numBottles;
while (numBottles >= numExchange) {
int newBottles = numBottles / numExchange;
total += newBottles;
numBottles = numBottles % numExchange + newBottles;
}
return total;
}
int main() {
std::cout << numWaterBottles(15, 4) << std::endl;
return 0;
}
This C++ solution calculates the sum of bottles gained through exchanges using a while loop, directly computing the additional drinks from exchanges.