Skip to content

Instantly share code, notes, and snippets.

@codertcet111
Created November 6, 2024 15:20
Show Gist options
  • Save codertcet111/63c578fd561f8f143e0b5673bd8ee021 to your computer and use it in GitHub Desktop.
Save codertcet111/63c578fd561f8f143e0b5673bd8ee021 to your computer and use it in GitHub Desktop.
leetcode 42 trapping rain water
=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
@codertcet111
Copy link
Author

Screenshot 2024-11-06 at 8 47 30 PM Memory beat 96%, run time only 8 ms

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