Table of Contents
Problem Statement
There are numBottles
water bottles that are initially full of water. You can exchange numExchange
empty water bottles from the market with one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Given the two integers numBottles
and numExchange
, return the maximum number of water bottles you can drink.
JAVA CODE Water Bottles
class Solution {
public int numWaterBottles(int numBottles, int numExchange) {
int fullBottles = numBottles;
int remainingEmptyBottles = 0;
int totalDrankBottles = 0;
totalDrankBottles += fullBottles;
int emptyBottles = fullBottles + remainingEmptyBottles;
while (emptyBottles >= numExchange){
fullBottles = emptyBottles / numExchange;
totalDrankBottles += fullBottles;
remainingEmptyBottles = emptyBottles % numExchange;
emptyBottles = fullBottles + remainingEmptyBottles;
}
return totalDrankBottles;
}
}
Better Clean Code Version
class Solution {
public int numWaterBottles(int numBottles, int numExchange) {
int totalDrankBottles = numBottles;
int emptyBottles = numBottles;
while (emptyBottles >= numExchange) {
int newFullBottles = emptyBottles / numExchange;
totalDrankBottles += newFullBottles;
emptyBottles = newFullBottles + (emptyBottles % numExchange);
}
return totalDrankBottles;
}
}
HINT
Simulate the process until there are not enough empty bottles for even one full bottle of water.
Leave a Reply