class Solution {
public int trap(int[] height) {
Stack<Integer> stack = new Stack<>();
int res = 0, water = 0;
for (int i = 0; i < height.length; i++) {
while (!stack.isEmpty() && height[stack.peek()] <= height[i]) {
int bottomIndex = stack.pop();
if (stack.isEmpty()) {
water = 0;
}
else {
int width = i - stack.peek() - 1;
int h = Math.min(height[stack.peek()], height[i]) - height[bottomIndex];
water = width * h;
}
res += water;
}
stack.push(i);
}
return res;
}
}