-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path042.rb
More file actions
35 lines (31 loc) · 645 Bytes
/
042.rb
File metadata and controls
35 lines (31 loc) · 645 Bytes
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
# @param {Integer[]} height
# @return {Integer}
def trap(height)
return 0 if height.length == 0
max_height = 0
max_index = -1
height.each_with_index do |h, i|
if h > max_height
max_height = h
max_index = i
end
end
volume = 0
current_max = 0
0.upto(max_index).each do |i|
if height[i] > current_max
current_max = height[i]
else
volume += (current_max - height[i])
end
end
current_max = 0
(height.length - 1).downto(max_index).each do |i|
if height[i] > current_max
current_max = height[i]
else
volume += (current_max - height[i])
end
end
volume
end