Skip to content

Commit 9540b5e

Browse files
Update optimized approach code and add explanation
1 parent 7495bc0 commit 9540b5e

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
Intuition
2+
We have to maximimse the bottles that we drink here so we clearly have to also maximise the empty bottles in every turn.
3+
4+
Approach
5+
To maximise the empty bottles in every turn we simply just have to drink in multiples of numExchange as much as we can and then we get the refills, We will continue this till we run out of sufficient bottles that can get us another refill, in the last we will add the remaining bottles that we did not drink in order to maximise our answer
6+
7+
Complexity
8+
Time complexity:
9+
O(n) We have to simulate our answer for different numbottles
10+
Is there a way to solve this in O(1) somehow? Let me knwo if there is!
11+
12+
Space complexity:
13+
O(1) We dont need any extra space for our solution

189-7th_July-Water_bottles/code.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution
2+
{
3+
public:
4+
int numWaterBottles(int numBottles, int numExchange)
5+
{
6+
int ans = numBottles, curBottles = 0;
7+
while (true)
8+
{
9+
if (numBottles - numExchange < 0)
10+
{
11+
ans += curBottles;
12+
numBottles += curBottles;
13+
curBottles = 0;
14+
}
15+
curBottles++;
16+
numBottles -= numExchange;
17+
if (numBottles < 0)
18+
break;
19+
}
20+
return ans;
21+
}
22+
};

0 commit comments

Comments
 (0)