MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / trap

Function trap

trapping_rain_water_42/solution.go:5–32  ·  view source on GitHub ↗
(height []int)

Source from the content-addressed store, hash-verified

3import "math"
4
5func 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.

Callers 1

Test_trapFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_trapFunction · 0.68