Trapping Rain Water
Given an elevation map where the width of each bar is 1, return the total amount of rainwater that can be trapped.
Examples
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Input: [4,2,0,3,2,5]
Output: 9
Hints
Keep a monotonic stack of indices whose heights are non-increasing from bottom to top. For each bar `i`, while the stack is non-empty and `height[stack.top] < height[i]`, pop the top as a valley floor: if the stack becomes empty there is no left wall and nothing is added, otherwise add `(min(height[stack.top], height[i]) - height[popped]) * (i - stack.top - 1)`. A bar is popped only by a strictly taller bar, so equal heights are never popped by each other and any pop between equal-height bars adds zero water.
Precompute the maximum height to the left and right of each bar in separate arrays, then iterate through the height array to sum the trapped water using these precomputed values.
Optimize space by using a single pass with two pointers: compare `height[left]` with `height[right]`, settle the side holding the smaller current bar, update that side's running maximum, and add water only when the settled bar sits below its running maximum.
Related Problems
Trapping Rain Water
Given an elevation map where the width of each bar is 1, return the total amount of rainwater that can be trapped.