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