package stack;
import java.util.Stack;
/**
* æ¥é¨æ°´
*/
public class Solution2 {
public int trap(int[] height) {
int result = 0;
Stack stack = new Stack();//å建ä¸ä¸ªåè°æ ,æ¯å°é¡¶åè°æ
for (int i = 0; i < height.length; i++) {
while (!stack.isEmpty() && height[stack.peek()] < height[i]){
Integer top = stack.pop();
if(stack.isEmpty()){
//æ 空 表示没æå¢äº
break;
}
//ç®åºå½åå¢é¢ä¸åé¢çå¢é¢ç¸éæ°
int destination = i - stack.peek() - 1;
int min = Math.min(height[stack.peek()], height[i]);
result += destination*(min - height[top]);
}
stack.push(i);
}
return result;
}
}