Water Bottles

Given numBottles full water bottles, you can exchange numExchange empty water bottles for one full water bottle.
The operation of drinking a full water bottle turns it into an empty bottle.
Find the maximum number of water bottles you can drink.

Example:

Input:  numBottles=9,numExchange=3
Output: 13

Approach

Java


public class WaterBottles {
    public static void main(String[] args) {
        int numBottles = 9;
        int numExchange = 3;
        int drink = numWaterBottles(numBottles, numExchange);
        System.out.println(drink);
    }

    static public int numWaterBottles(int numBottlesint numExchange) {
        // base case
        if (numBottles < numExchange)
            return numBottles;

        int drink = numBottles;
        while (numBottles > 0 && numBottles >= numExchange) {
            int remE = numBottles % numExchange;
            drink += numBottles / numExchange;
            numBottles = remE + numBottles / numExchange;
        }
        return drink;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

//function to count the number of bottles

int numWaterBottles(int numBottlesint numExchange
{
    int ans=numBottles;
    int x=ans;
    while(x>=numExchange)
       {
          ans+=x/numExchange;
       
         int y=x%numExchange;
         x=x/numExchange;
         x=x+y;
       }
        return ans;
}
int main()
{
    int numBottles=9;
    int numExchange=3;
    cout<<numWaterBottles(numBottles,numExchange);
    return 0;
}


No comments:

Post a Comment