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
Use a stack to keep track of indices where the current height is less than the previous height, and calculate trapped water whenever a higher bar is encountered.
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, dynamically updating leftMax and rightMax while calculating trapped water based on the smaller of the two.