Skip to content

1518. Water Bottles 👍

Approach 1: $O(\log numBottles)$ space

  • Time: $O(\log numBottles)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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;
  }
};

Approach 2: $O(1)$ space

  • Time: $O(1)$
  • Space: $O(1)$
1
2
3
4
5
6
class Solution {
 public:
  int numWaterBottles(int numBottles, int numExchange) {
    return numBottles + (numBottles - 1) / (numExchange - 1);
  }
};