Given an elevation map (array height[]), compute how much water it can trap after raining. Solve using a monotonic stack.
Use a monotonic decreasing stack of indices. When we find a bar taller than the stack top, water can be trapped between the current bar, the popped bar, and the new stack top (left boundary).
- Maintain a stack of indices with decreasing heights.
- For each bar i: while stack non-empty and height[i] > height[stack.top()]:
- Pop mid = stack.pop(). If stack is empty break.
- Width = i - stack.top() - 1, bounded height = min(height[i], height[stack.top()]) - height[mid]. Add width * bounded height to water.
- Time Complexity: O(N)
- Space Complexity: O(N)