| 3 | import "math" |
| 4 | |
| 5 | func trap(height []int) int { |
| 6 | left := 0 |
| 7 | leftMax := 0 |
| 8 | right := len(height) - 1 |
| 9 | rightMax := 0 |
| 10 | count := 0 |
| 11 | |
| 12 | for left < right { |
| 13 | leftMax = int(math.Max(float64(height[left]), float64(leftMax))) |
| 14 | rightMax = int(math.Max(float64(height[right]), float64(rightMax))) |
| 15 | |
| 16 | if height[left] < height[right] { |
| 17 | left++ |
| 18 | } else { |
| 19 | right-- |
| 20 | } |
| 21 | |
| 22 | if leftMax > height[left] && leftMax < rightMax { |
| 23 | count += leftMax - height[left] |
| 24 | } |
| 25 | |
| 26 | if rightMax > height[right] && leftMax >= rightMax { |
| 27 | count += rightMax - height[right] |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | return count |
| 32 | } |
| 33 | |
| 34 | // trap2 worked, but ran out of memory on leetcode. |
| 35 | // This was my first pass at the problem. |