You have numBottles
full water bottles. You drink one bottle of water and eventually recycle it, getting one empty bottle.
For every numExchange
empty bottles you can get one full water bottle.
The task is to find the maximum number of water bottles you can drink.
Q: Can the values of numBottles
and numExchange
be zero or negative?
A: The problem constraints clarify that these values will be positive integers.
Q: Is there an upper limit on the values for numBottles
and numExchange
?
A: Constraints typically ensure that these values are within a reasonable range to compute within time limits.
Q: Are there any other edge cases to consider (like numBottles < numExchange
)?
A: If numBottles
is less than numExchange
, you cannot exchange any bottles, so the number of bottles you drink will just be numBottles
.
numBottles
full bottles.numExchange
.The time complexity of the solution will be O(log(numBottles)) since in each iteration, the number of bottles reduces significantly.
public class Solution {
public int numWaterBottles(int numBottles, int numExchange) {
int totalDrunk = 0;
int emptyBottles = 0;
while (numBottles > 0) {
// Drink all current full bottles
totalDrunk += numBottles;
emptyBottles += numBottles;
numBottles = 0;
// Exchange empty bottles for full bottles
numBottles = emptyBottles / numExchange;
emptyBottles = emptyBottles % numExchange;
}
return totalDrunk;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test case 1
System.out.println(solution.numWaterBottles(9, 3)); // Output: 13
// Test case 2
System.out.println(solution.numWaterBottles(15, 4)); // Output: 19
// Test case 3
System.out.println(solution.numWaterBottles(5, 5)); // Output: 6
// Test case 4
System.out.println(solution.numWaterBottles(2, 3)); // Output: 2
}
}
numBottles
full bottles.totalDrunk
.By following this approach, we ensure an efficient and correct solution to the problem.
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?