1518: Water-Bottles
Easy


table of contents

Initialise an ans variable to track the answer - it will be set to numBottles initially, since we are definitely drinking numBottles of water.

Then, while numBottles >= numExchange, it implies that we can still exchange our empty bottles for new ones. This means while the above inequality is true, we can simply add numBottles / numExchange to our ans (as these are the full bottles of water we are exchanging for) and then update our existing numBottles count with numBottles / numExchange + numBottles % numExchange.

code

class Solution {
public:
    int numWaterBottles(int numBottles, int numExchange) {
        int ans = numBottles;
        while (numBottles >= numExchange) {
            ans += numBottles / numExchange;
            numBottles = numBottles / numExchange + numBottles % numExchange;
        }
        return ans;
    }
};

complexity

time taken