Here's the stack solution:
function trap(height)
stack := empty stack // stores indices
water := 0
for i from 0 to length of height - 1
while stack is not empty and height[i] > height[top of stack]
mid := pop from stack
if stack is empty
break // no left boundary
left := top of stack
width := i - left - 1
h := min(height[i], height[left]) - height[mid]
water := water + width × h
push i onto stack
return water
Time: . Space: .