Created
November 6, 2024 15:20
-
-
Save codertcet111/63c578fd561f8f143e0b5673bd8ee021 to your computer and use it in GitHub Desktop.
leetcode 42 trapping rain water
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
=begin | |
42. Trapping Rain Water | |
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. | |
Example 1: | |
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] | |
Output: 6 | |
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. | |
Example 2: | |
Input: height = [4,2,0,3,2,5] | |
Output: 9 | |
=end | |
def trap(height) | |
max = height[0] | |
max_i = 0 | |
water = 0 | |
# from forward | |
(1..(height.length - 1)).each do |i| | |
if height[i] >= max | |
((max_i + 1)...i).each do |j| | |
water += max - height[j] | |
end | |
max = height[i] | |
max_i = i | |
end | |
end | |
until_max_i = max_i | |
# from backward | |
max = height[-1] | |
max_i = height.length - 1 | |
(until_max_i..(height.length - 2)).reverse_each do |i| | |
if height[i] >= max | |
((i+1)..(max_i - 1)).each do |j| | |
water += max - height[j] | |
end | |
max = height[i] | |
max_i = i | |
end | |
end | |
water | |
end |
Author
codertcet111
commented
Nov 6, 2024

Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment