Ideas:
Observation shows that if the height of the current column is greater than the height of the previous column, it will be popped out of the stack, and the height of one column will be obtained further, that is, 3 columns will be used. Get the area between the two higher pillars. As you can see, you need to use a monotonic stack
class Solution {
public int trap(int[] height) {
int n=height.length;
Deque<Integer> stack=new ArrayDeque<>();
int sum=0;
for(int i=0;i<n;i++){
//分为了3个柱子
while(!stack.isEmpty()&&height[i]>height[stack.peekLast()]){
//第二根柱子
int pop=stack.pollLast();
//若前面没有了(第一根柱子),就退出循环,必须要满足3个柱子
if(stack.isEmpty()) break;
//这里的stack.peekLast()表示第一根柱子
//high表示头尾2根较矮一根的高度-中间柱子的高度
int high=Math.min(height[i],height[stack.peekLast()])-height[pop];
int width=i-stack.peekLast()-1;
sum+=high*width;
}
stack.addLast(i);
}
return sum;
}
}