class Solution {
public int trap(int[] height) {
int leftMax = 0;
int rightMax = 0;
int i = 0;
int j = height.length-1;
int sum = 0;
while (i <= j) {
leftMax = Math.max(leftMax, height[i]);
rightMax = Math.max(rightMax, height[j]);
if (leftMax < rightMax) {
// i左边的bar已经探索完了,leftMax确定是它的短板了,所以它能装的水就固定了
sum += leftMax - height[i++];
} else {
sum += rightMax - height[j--];
}
}
return sum;
}
}
class Solution {
public int trap(int[] height) {
// decreasing stack
Deque<Integer> stack = new ArrayDeque<>();
int sum = 0;
for (int i = 0; i < height.length; i++) {
while (!stack.isEmpty() && height[stack.peek()] < height[i]) {
int idx = stack.pop();
if (stack.isEmpty()) {
continue;
}
int left = stack.peek();
int right = i;
sum += (right - left - 1) * (Math.min(height[left], height[right])-height[idx]);
}
stack.push(i);
}
return sum;
}
}