-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1518-Water_Bottles.cpp
More file actions
86 lines (78 loc) · 2.09 KB
/
1518-Water_Bottles.cpp
File metadata and controls
86 lines (78 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*******************************************************************************
* 1518-Water_Bottles.cpp
* Billy.Ljm
* 07 July 2024
*
* =======
* Problem
* =======
* https://leetcode.com/problems/water-bottles/
*
* 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.
*
* ===========
* My Approach
* ===========
* You can drink n*k bottles every step and exchange them for n filled bottles.
* Repeat this until you have less than k bottles left, and just drink the rest.
*
* This has a time complexity of O(log_k n) and space complexity of O(1), where n
* is numBottles and k is numExchange.
******************************************************************************/
#include <iostream>
#include <vector>
using namespace std;
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (const auto elem : v) {
os << elem << ",";
}
if (v.size() > 0) os << "\b";
os << "]";
return os;
}
/**
* Solution
*/
class Solution {
public:
int numWaterBottles(int numBottles, int numExchange) {
int mult;
int cnt = 0;
while (numBottles >= numExchange) {
mult = numBottles / numExchange;
cnt += mult * numExchange;
numBottles -= mult * (numExchange - 1);
}
return cnt + numBottles;
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
int numBottles, numExchange;
// test case 1
numBottles = 9;
numExchange = 3;
std::cout << "numWaterBottles(" << numBottles << ", " << numExchange << ") = ";
std::cout << sol.numWaterBottles(numBottles, numExchange) << std::endl;
// test case 2
numBottles = 15;
numExchange = 4;
std::cout << "numWaterBottles(" << numBottles << ", " << numExchange << ") = ";
std::cout << sol.numWaterBottles(numBottles, numExchange) << std::endl;
return 0;
}