Pour Water Between Buckets to Make Water Levels Equal — LeetCode 2137 Python Solution
- Problem
- #2137
- Pattern
- Monotonic Stack
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You have n buckets each containing some gallons of water in it, represented by a 0-indexed integer array buckets, where the ith bucket contains buckets[i] gallons of water. You are also given an integer loss.
Example
- Input
- buckets = [1,2,7], loss = 80
- Output
- 2.00000
- Explanation
- Pour 5 gallons of water from buckets[2] to buckets[0].
Python solution
class Solution:
def equalizeWater(self, buckets: List[int], loss: int) -> float:
def check(v):
a = b = 0
for x in buckets:
if x >= v:
a += x - v
else:
b += (v - x) * 100 / (100 - loss)
return a >= b
l, r = 0, max(buckets)
while r - l > 1e-5:
mid = (l + r) / 2
if check(mid):
l = mid
else:
r = mid
return lComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M), where n and M are the length and the maximum value of the array buckets, respectively |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2137. Pour Water Between Buckets to Make Water Levels Equal is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2137. Pour Water Between Buckets to Make Water Levels Equal?
- LeetCode 2137. Pour Water Between Buckets to Make Water Levels Equal is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2137. Pour Water Between Buckets to Make Water Levels Equal?
- The Python solution on this page runs in O(n \times \log M), where n and M are the length and the maximum value of the array buckets, respectively.
- What is the space complexity of LeetCode 2137. Pour Water Between Buckets to Make Water Levels Equal?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2137. Pour Water Between Buckets to Make Water Levels Equal cover?
- LeetCode 2137. Pour Water Between Buckets to Make Water Levels Equal is tagged Array and Binary Search on LeetCode.
- Is LeetCode 2137. Pour Water Between Buckets to Make Water Levels Equal a premium problem?
- Yes. LeetCode 2137. Pour Water Between Buckets to Make Water Levels Equal is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.