# 原地址
https://leetcode-cn.com/problems/trapping-rain-water/
# 分析
- 从开始遍历数组
- 在遍历中分别找到左边最大值和右边最大值
- 然后比较左边和右边哪个最小,用最小的减去当前位置的,就得到接雨水的量。
# 代码
```java
class Solution {
public int trap(int[] height) {
int count = 0;
for(int i = 0; i < height.length; i++){
int leftMax = 0;
int rightMax = 0;
// left
for(int k = i-1; k >= 0; k--){
leftMax = leftMax >= height[k] ? leftMax : height[k];
}
// right
for(int j = i+1; j < height.length; j++){
rightMax = rightMax >= height[j] ? rightMax : height[j];
}
if(height[i]<leftMax && height[i]< rightMax){
int minHeight = leftMax >= rightMax? rightMax : leftMax;
count += minHeight - height[i];
height[i] = minHeight;
}
}
return count;
}
}
```
# 代码优化
```java
class Solution {
public int trap(int[] height) {
int count = 0;
int left = 0, right = height.length - 1;
int left_max = 0, right_max = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= left_max) {
left_max = height[left];
} else {
// 接雨水
count += (left_max - height[left]);
}
++left;
} else {
if (height[right] >= right_max) {
right_max = height[right];
} else {
// 接雨水
count += (right_max - height[right]);
}
--right;
}
}
return count;
}
}
```

42. 接雨水