```java
class Solution {
public int trap(int[] height) {
int n = height.length;
Stack<Integer> stack = new Stack<>(); // index
int result = 0;
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && height[stack.peek()] < height[i]) {
int base = height[stack.pop()];
if (!stack.isEmpty()) {
int leftBoundIndex = stack.peek();
int leftHeight = height[leftBoundIndex];
result += (Math.min(height[i], leftHeight) - base)*(i - leftBoundIndex - 1);
}
}
stack.push(i);
}
return result;
}
}
/***
min(hi, left side) - base idea
2,1,0,1,3
x x x
3
2.x x x 3
2 1 x 1 3
2 1 0.1 3
curH
base = pop
left = peek
(min(leftH, curH) - base)* (index diff)
3
2.x x x 3
2 1 x 1 3
3. cur H
1 -> base
1. -> peek
2 -> peek
min(3, 1) - base (1) = 0
min(3, 2) - base (1) = 1
*/
```
if (height[left] < height[right]) { // ๅ ็บๅทฆ้ๆฏ่ผๅฐ, ๅ ๅ left
....
left++;
class Solution {
public int trap(int[] height) {
// two pointers
// h[left] > h[right]
// leftmax > h[left] => res += leftmax - res
int left = 0;
int right = height.length - 1;
int leftMax = 0;
int rightMax = 0;
int res = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(leftMax, height[left]);
res += leftMax - height[left];
left++;
} else {
rightMax = Math.max(rightMax, height[right]);
res += rightMax - height[right];
right--;
}
}
return res;
}
}
class Solution {
public int trap(int[] height) {
int n = height.length;
int left = 0;
int right = n-1;
int maxLeft = 0;
int maxRight = 0;
int result = 0;
while (left < right) {
maxLeft = Math.max(maxLeft, height[left]);
maxRight = Math.max(maxRight, height[right]);
if (maxLeft < maxRight) {
result += maxLeft - height[left];
left++;
} else {
result += maxRight - height[right];
right--;
}
}
return result;
}
}
class Solution {
public int trap(int[] height) {
int n = height.length;
int[] maxLeft = new int[n];
int[] maxRight = new int[n];
maxLeft[0] = height[0];
for (int i = 1; i < n; i++) {
maxLeft[i] = Math.max(height[i], maxLeft[i-1]);
}
maxRight[n-1] = height[n-1];
for (int i = n-2; i >= 0; i--) {
maxRight[i] = Math.max(height[i], maxRight[i+1]);
}
int result = 0;
for (int i = 0; i < n; i++) {
result += Math.min(maxLeft[i] , maxRight[i]) - height[i];
}
return result;
}
}