给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

**输入:height = [0,1,0,2,1,0,1,3,2,1,2,1] 输出:6 解释:上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。
思路:
- A1. 要素:
- 柱高 ():当前位置的地面高度。
- 左最值 ():当前位置左侧所有柱子中最的那根。
- 右最值 ():当前位置右侧所有柱子中最的那根。
- A2. 结构:
- 水位公式:。
- 积水公式:
function trap(height: number[]): number {
let l_max = 0
let r_max = 0
let left =0
let right = height.length -1
let res =0
let n=height.length
while(left<right){
//更新l_max与 r_max的值
l_max = Math.max(l_max, height[left]);
r_max = Math.max(r_max, height[right]);
if(l_max>r_max){
res += r_max - height[right]
right --
}else {
res +=l_max - height[left]
left ++
}
}
return res
};