# 42. Trapping Rain Water

**<font color=red>难度: Hard</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/trapping-rain-water/description/

> 内容描述

```
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
```

![](https://github.com/apachecn/awesome-algorithm/blob/master/images/042/rainwatertrap.png)

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
```
Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

题目有几个特性可用，bar width = 1,然后第一个和最后一个是不能trap water，其次中间的部分能trap多少水是看`左右高度差较低的那个 -  本身的高度`

The basic idea is that we set two pointers ```l``` and ```r``` to the left and right end of ```height```. Then we get the minimum height (```min_height```) of these pointers (similar to Container with Most Water due to the Leaking Bucket Effect) since the level of the water cannot be higher than it. Then we move the two pointers towards the center. If the coming level is less than ```min_height```, then it will hold some water. Fill the water until we meet some “barrier” (with height larger than ```min_height```) and update ```l``` and ```r``` to repeat this process in a new interval.

AC代码：

beats 100%
```python
class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        l, r, water, min_height = 0, len(height) - 1, 0, 0
        while l < r:
            min_height = min(height[l], height[r])
            while l < r and height[l] <= min_height:
                water += min_height - height[l] 
                l += 1
            while l < r and height[r] <= min_height:
                water += min_height - height[r]
                r -= 1
        return water
```
