# 42. Trapping Rain Water

{% hint style="info" %}

```java
        // let w(i) represent the amount of water trapped at position i
        // h(left) represent the highest height on left of i, 
        // h(right) represent the highest height on the right of i,
        // w(i) = min(h(left), h(right)) - h(i);
```

{% endhint %}

### DP:

```java
class Solution {
    public int trap(int[] height) {
        int[] l = new int[height.length];
        int[] r = new int[height.length];
        int leftMax = 0;
        for(int i = 0; i<height.length; i++){
            leftMax = i == 0 ?  height[i] : Math.max(l[i-1], height[i]);
            l[i] = leftMax;
        }
        
        int rightMax = 0;
        for (int j= height.length-1; j>=0; j--){
            rightMax = j == height.length-1 ? height[j] : Math.max(height[j], r[j+1]);
            r[j] = rightMax;
        }
        
        int sum = 0;
        for (int k = 0; k<height.length; k++){
            sum += Math.min(l[k], r[k])-height[k];
        }
        return sum;
    }
}
```

### Two pointers:

```java
class Solution {
    public int trap(int[] height) {
        int l = 0;
        int r = height.length-1;
        
        //represent the maxium height in the range [0, l];
        int maxL = 0;
        //represent the maxium height in the range [r, height.length-1];
        int maxR = 0;
        int sum = 0;
        while(l<r){
            maxL = Math.max(maxL, height[l]);
            maxR = Math.max(maxR, height[r]);
            if (maxL<=maxR){
                sum+=maxL-height[l];
                l++;
            }else{
                sum += maxR-height[r];
                r--;
            }
        }
        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://ucan.gitbook.io/notes/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.
