import java.util.Stack;
public class Solution {
public int trap(int[] A) {
if(null == A || A.length < 3)
return 0;
int sum = 0,i = 0;
Stack<Integer> stack = new Stack<Integer>();
while(i < A.length){
if(stack.isEmpty() || A[stack.peek()] >= A[i]){
stack.push(i++);
}else{
int bottom = A[stack.pop()];
if(!stack.isEmpty()){
int high = Math.min(A[i], A[stack.peek()]);
int length = i - stack.peek() - 1;
sum += (high - bottom) * length;
}
}
}
return sum;
}
}