-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path42_trapping_rain_water.rb
More file actions
45 lines (42 loc) · 909 Bytes
/
42_trapping_rain_water.rb
File metadata and controls
45 lines (42 loc) · 909 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
36
37
38
39
40
41
42
43
44
45
# @param {Integer[]} height
# @return {Integer}
def calculate_amount(height)
heighest = height[0]
amount = 0
tmp_amount = 0
height.each do |h|
if h >= heighest
amount += tmp_amount
tmp_amount = 0
heighest = h
else
tmp_amount += heighest - h
end
end
return amount
end
def trap(height)
heighest = height[0]
traps = []
trap = []
height.each do |h|
if h >= heighest && trap.size > 0
heighest = h
trap << h
traps << trap if trap.size >= 3
trap = [h]
else
trap << h
end
end
traps << trap if trap.size >= 3
amount = 0
traps.each do |trap|
if trap[0] > trap[trap.size - 1]
amount += calculate_amount(trap.reverse)
else
amount += calculate_amount(trap)
end
end
return amount
end