Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e815ef4

Browse files
Merge pull request neetcode-gh#356 from seungjun-green/patch-1
Create 42-Trapping-Rain-Water.swift
2 parents 8bb7a5a + d14453f commit e815ef4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

swift/42-Trapping-Rain-Water.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
func trap(_ height: [Int]) -> Int {
3+
if height == nil {
4+
return 0
5+
}
6+
7+
var res = 0
8+
var l = 0
9+
var r = height.count - 1
10+
11+
var leftMax = height[l]
12+
var rightMax = height[r]
13+
14+
while l < r {
15+
if leftMax < rightMax {
16+
l += 1
17+
leftMax = max(leftMax, height[l])
18+
res += leftMax - height[l]
19+
} else {
20+
r -= 1
21+
rightMax = max(rightMax, height[r])
22+
res += rightMax - height[r]
23+
}
24+
}
25+
26+
return res
27+
28+
}
29+
30+
}

0 commit comments

Comments
 (0)