[LeetCode] Pour Water Between Buckets to Make Water Levels Equal

2137. Pour Water Between Buckets to Make Water Levels Equal

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.

You want to make the amount of water in each bucket equal. You can pour any amount of water from one bucket to another bucket (not necessarily an integer). However, every time you pour k gallons of water, you spill loss percent of k.

Return the maximum amount of water in each bucket after making the amount of water equal. Answers within 10-5 of the actual answer will be accepted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
long double EPS = 1e-5;
bool helper(vector<int>& A, int loss, long double m) {
long double less = 0.0, greater = 0.0;
for(auto& a : A) {
if(a < m) less += m - a;
else greater += a - m;
}
return greater * (1 - loss/100.) >= less;
}
public:
double equalizeWater(vector<int>& A, int loss) {
sort(begin(A), end(A));
long double l = A[0], r = A.back();

while(l + EPS < r) {
long double m = l + (r-l) / 2.0;
bool pass = helper(A, loss, m);
if(pass) l = m;
else r = m;
}
return l;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/03/PS/LeetCode/pour-water-between-buckets-to-make-water-levels-equal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.