You have numBottles
full water bottles and you can exchange numExchange
empty water bottles for one full water bottle.
The task is to write a function that returns the maximum number of water bottles you can drink.
Example 1:
Input: numBottles = 9, numExchange = 3
Output: 13
Explanation: You can exchange 3 empty bottles to get 1 full water bottle.
Example 2:
Input: numBottles = 15, numExchange = 4
Output: 19
Explanation: You can exchange 4 empty bottles to get 1 full water bottle.
numBottles
and numExchange
always positive integers?
To solve the problem, follow these steps:
numBottles
.#include <iostream>
int numWaterBottles(int numBottles, int numExchange) {
int totalDrunk = numBottles;
int emptyBottles = numBottles;
while (emptyBottles >= numExchange) {
int newBottles = emptyBottles / numExchange;
totalDrunk += newBottles;
emptyBottles = newBottles + (emptyBottles % numExchange);
}
return totalDrunk;
}
int main() {
// Test cases
std::cout << numWaterBottles(9, 3) << std::endl; // should output 13
std::cout << numWaterBottles(15, 4) << std::endl; // should output 19
return 0;
}
The time complexity of this algorithm is O(log(numBottles)) because, in each iteration, the number of empty bottles is divided by at least numExchange
, reducing the number of empty bottles logarithmically. This makes the approach efficient even for larger values of numBottles
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?