-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtrap.go
More file actions
38 lines (33 loc) · 845 Bytes
/
Copy pathtrap.go
File metadata and controls
38 lines (33 loc) · 845 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
/* https://leetcode.com/problems/trapping-rain-water/description/
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.
http://www.leetcode.com/static/images/problemset/rainwatertrap.png
*/
package larray
func trap(height []int) int {
// 2 pointers
var (
left, right = 0, len(height) - 1
res = 0
leftMax, rightMax = 0, 0
)
for left < right {
if height[left] < height[right] {
if height[left] >= leftMax {
leftMax = height[left]
} else {
res += leftMax - height[left]
}
left++
} else {
if height[right] >= rightMax {
rightMax = height[right]
} else {
res += rightMax - height[right]
}
right--
}
}
return res
}