# 42 Trapping rain water

跟11的思路很像，初见杀很难想到吧。

```java
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;
    }
}
```

更容易想到的思路是mono stack，但是要记得mono stack只能找到第一个大的值，但是能装多少取决于最大值，所以思路是固定水的底，然后一层一层往上加，举个例子就

<figure><img src="/files/scTzvzsAkBnWBkhrDEat" alt=""><figcaption><p>方法1是这样的</p></figcaption></figure>

<figure><img src="/files/OMTZVZ73LxAB61c2raYk" alt=""><figcaption><p>用mono stack是这样的</p></figcaption></figure>

```java
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;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hzhang.gitbook.io/leetcode-record/2-pointer-including-sliding-window/42-trapping-rain-water.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
