Golang:

func trap(height []int) int {
n := len(height)
l, r, water, minHeight := 0, n-1, 0, 0
for l < r {
for l < r && height[l] <= minHeight {
water += minHeight - height[l]
l+= 1
}
for r > l && height[r] <= minHeight {
water += minHeight - height[r]
r-=1
}
minHeight = min(height[l], height[r])
}
return water
}
func min(a, b int) int {
if a < b {
return a
} else {
return b
}
}

Javascript version:

var trap = function(height) {
var n = height.length
var l = 0, r = n - 1, water= 0, minHeight = 0
while(l < r) {
while(l < r && height[l] <= minHeight) {
water += minHeight - height[l]
l+= 1
}
while(r > l && height[r] <= minHeight) {
water += minHeight - height[r]
r-=1
}
minHeight = Math.min(height[l], height[r])
}
return water
};