# 2137. Pour Water Between Buckets to Make Water Levels Equal    • Time: $O(n\log \frac{\max}{10^{-5}})$
• Space: $O(1)$
  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 class Solution { public: double equalizeWater(vector& buckets, int loss) { constexpr double kErr = 1e-5; const double kPercentage = (100 - loss) / (double)100; double l = 0.0; double r = *max_element(begin(buckets), end(buckets)); while (r - l > kErr) { const double m = (l + r) / 2; if (canFill(buckets, m, kPercentage)) l = m; else r = m; } return l; } private: bool canFill(const vector& buckets, double target, double kPercentage) { double extra = 0.0; double need = 0.0; for (const int bucket : buckets) if (bucket > target) extra += bucket - target; else need += target - bucket; return extra * kPercentage >= need; } }; 
  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 class Solution { public double equalizeWater(int[] buckets, int loss) { final double kErr = 1e-5; final double kPercentage = (100 - loss) / (double) 100; double l = 0.0; double r = Arrays.stream(buckets).max().getAsInt(); while (r - l > kErr) { final double m = (l + r) / 2; if (canFill(buckets, m, kPercentage)) l = m; else r = m; } return l; } private boolean canFill(int[] buckets, double target, double kPercentage) { double extra = 0.0; double need = 0.0; for (final int bucket : buckets) if (bucket > target) extra += bucket - target; else need += target - bucket; return extra * kPercentage >= need; }; } 
  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 class Solution: def equalizeWater(self, buckets: List[int], loss: int) -> float: kErr = 1e-5 kPercentage = (100 - loss) / 100 l = 0.0 r = max(buckets) def canFill(target: float) -> bool: extra = 0 need = 0 for bucket in buckets: if bucket > target: extra += bucket - target else: need += target - bucket return extra * kPercentage >= need while r - l > kErr: m = (l + r) / 2 if canFill(m): l = m else: r = m return l