Leetcode Problem 2137. Pour Water Between Buckets to Make Water Levels Equal

2137. Pour Water Between Buckets to Make Water Levels Equal

Leetcode Solutions

Binary Search to Find the Maximum Equal Water Level

Algorithm

  1. Initialize left to the minimum water level in any bucket and right to the average water level across all buckets.
  2. Calculate the left_over ratio as 1 - loss / 100.
  3. Define a function ok(val) that checks if a water level val is achievable:
    • Initialize a counter cnt to 0.
    • Iterate over each bucket:
      • If the bucket has more water than val, add the excess water times left_over to cnt.
      • If the bucket has less water than val, subtract the deficit from cnt.
    • Return True if cnt is non-negative, indicating that the level is achievable.
  4. Perform binary search:
    • While right - left is greater than the precision threshold:
      • Calculate mid as the average of left and right.
      • If ok(mid) returns True, update left to mid; otherwise, update right to mid.
    • Return right as the maximum achievable water level.
UML Thumbnail

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...