Created
July 2, 2020 21:09
-
-
Save franzese/8251377214e8e274a38c475b0b816fdb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def remaining_water(height) | |
# some boundary checking, height is nil, height is emtpy? | |
left_point = 0 | |
right_point = 0 | |
water_remaining = 0 | |
left = 0 | |
right = height.length - 1 | |
while left < right | |
if height[left] < height[right] | |
left_point = [height[left], left_point].max | |
water_remaining += (left_point - height[left]) | |
left += 1 | |
else | |
right_point = [height[right], right_point].max | |
water_remaining += (right_point - height[right]) | |
right -= 1 | |
end | |
end | |
water_remaining | |
end | |
puts remaining_water([3,0,0,2,0,5]) # 10 | |
puts remaining_water([5,0,2,0,0,3]) # 10 | |
puts remaining_water([0,3,0,0,2,0,5,0,2]) # 12 | |
puts remaining_water([0,2,0,3,2,1,1,2,1]) # 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment