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).
1function numWaterBottles(numBottles, numExchange) {
2 let totalDrank = numBottles;
3 let emptyBottles = numBottles;
4 while (emptyBottles >= numExchange) {
5 let newBottles = Math.floor(emptyBottles / numExchange);
6 totalDrank += newBottles;
7 emptyBottles = emptyBottles % numExchange + newBottles;
8 }
9 return totalDrank;
10}
11
12console.log(numWaterBottles(9, 3));
The JavaScript code uses a while loop to repeatedly simulate drinking and exchanging operations, adjusting the total drunk count accordingly.
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>
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.