Concept Flow - Trapping Rain Water Using Stack
Start with empty stack
Iterate over height array
While stack not empty and current height > height at stack top
Pop top from stack as bottom
If stack empty after pop, break loop
Calculate distance between current and new stack top
Calculate bounded height
Add trapped water: distance * bounded height
Push current index to stack
Repeat until end of array
Return total trapped water
We use a stack to keep track of bars. When a taller bar comes, we pop shorter bars and calculate trapped water between the current bar and the new top of stack.
