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).
1#include <stdio.h>
2
3int numWaterBottles(int numBottles, int numExchange) {
4 int totalDrank = numBottles;
5 int emptyBottles = numBottles;
6 while (emptyBottles >= numExchange) {
7 int newBottles = emptyBottles / numExchange;
8 totalDrank += newBottles;
9 emptyBottles = emptyBottles % numExchange + newBottles;
10 }
11 return totalDrank;
12}
13
14int main() {
15 int numBottles = 9, numExchange = 3;
16 printf("%d\n", numWaterBottles(numBottles, numExchange));
17 return 0;
18}
The function numWaterBottles
calculates the maximum number of water bottles one can drink. It uses a loop to repeatedly simulate drinking and exchanging bottles while keeping track of total bottles drunk and current empty bottles.
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).
1function
This JavaScript solution conducts direct updates to total bottles with new exchanges calculated in a loop, efficiently tallying maximum drinks.