Use a monotonic decreasing stack. When you encounter a bar taller than the stack top:
Pop the top (the popped element forms a valley)
If stack is now empty, no water can be trapped
Otherwise, calculate water between current bar, popped bar, and new top The water at this layer has width and height . Accumulate water as you pop.