-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathtrapping_rain_water.rb
44 lines (39 loc) · 1.06 KB
/
trapping_rain_water.rb
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
32
33
34
35
36
37
38
39
40
41
42
43
44
# https://leetcode.com/problems/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 is able to trap after raining.
#
# For example, Given [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1], return 6.
#
# ^
# |
# |
# | ||||
# | ||||
# | ||||************||||||||****||||
# | ||||************||||||||****||||
# | ||||****||||||||****||||||||||||||||||||||||
# | ||||****||||||||****||||||||||||||||||||||||
# +---------------------------------------------------->
# @param {Integer[]} height
# @return {Integer}
def trap(height)
lbound, ubound = 0, height.size - 1
boundheight, capacity = 0, 0
while lbound < ubound
lh, uh = height[lbound], height[ubound]
if lh < uh
lbound += 1
h = lh
else
ubound -= 1
h = uh
end
if h > boundheight
boundheight = h
else
capacity += boundheight - h
end
end
capacity
end