Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9ad3ada

Browse files
committed
42
1 parent4b025fe commit9ad3ada

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎ruby/42-Trapping-Rain-Water.rb‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
deftrap(height)
2+
max_left=[]
3+
max_right=[]
4+
5+
max=0
6+
height.eachdo |line|
7+
max_left <<max
8+
max=lineifline >max
9+
end
10+
11+
max=0
12+
(height.length -1).downto(0).eachdo |idx|
13+
max_right.unshift(max)
14+
max=height[idx]ifheight[idx] >max
15+
end
16+
17+
total_water=0
18+
height.each_with_indexdo |line,idx|
19+
min=max_left[idx] >max_right[idx] ?max_right[idx] :max_left[idx]
20+
water=min -line
21+
nextifwater <1
22+
23+
total_water +=water
24+
end
25+
total_water
26+
end
27+
28+
# 0(1) space
29+
deftrap(height)
30+
max_water=0
31+
max_left=height.first
32+
max_right=height.last
33+
left=0
34+
right=height.length -1
35+
36+
whileleft <right
37+
ifmax_left >max_right
38+
right -=1
39+
water=max_right -height[right]
40+
max_right=height[right]ifheight[right] >max_right
41+
else
42+
left +=1
43+
water=max_left -height[left]
44+
max_left=height[left]ifheight[left] >max_left
45+
end
46+
max_water +=waterunlesswater <1
47+
end
48+
max_water
49+
end

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp