Water Bottles II Solution in Java

Problem Description

Welcome to the world of Water Bottles II, where you can drink your way to glory! Imagine you have a certain number of water bottles, and you can exchange empty bottles for new ones. Sounds like a dream, right? But wait, there’s a catch! You can only exchange a specific number of empty bottles at a time.

Let’s say you have 9 bottles and you can exchange 3 empty ones for 1 full one. You might think, “I’ll just keep drinking and exchanging until I can’t anymore!” But alas, the universe has other plans. The goal is to figure out how many bottles you can drink in total before you’re left with nothing but regrets and empty bottles.

Code Solution


class Solution {
  public int maxBottlesDrunk(int numBottles, int numExchange) {
    int ans = numBottles;

    while (numBottles >= numExchange) {
      numBottles = (numBottles - numExchange + 1);
      ++numExchange;
      ++ans;
    }

    return ans;
  }
}

Approach

The approach here is as simple as it is effective. You start with the total number of bottles you have and keep exchanging them for new ones as long as you meet the exchange criteria. Each time you successfully exchange, you increment your total count of bottles drunk. It’s like a never-ending cycle of hydration!

Time and Space Complexity

Time Complexity

O(n), where n is the number of bottles you can drink. This is because in the worst case, you might have to loop through all the bottles until you can no longer exchange.

Space Complexity

O(1), since we are using a constant amount of space regardless of the input size.

Real-World Example

Imagine you’re at a party with a limited supply of drinks. You start with 10 bottles of soda. For every 3 empty bottles you return, you get 1 new bottle. You keep drinking and exchanging until you can’t anymore. By the end of the night, you’ve not only quenched your thirst but also made a few friends along the way. This is essentially what the Water Bottles II problem is all about!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in Java
  • 3-Sum Solution in Java