42. Trapping Rain Water
Mono Stack
```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
*/
```Two pointers
descending!


use this
Last updated

