給定 n
個非負整數表示每個寬度爲 1
的柱子的高度圖,計算按此排列的柱子,下雨之後能接多少雨水。
上面是由數組 [0,1,0,2,1,0,1,3,2,1,2,1]
表示的高度圖,在這種情況下,可以接 6
個單位的雨水(藍色部分表示雨水)。 感謝 Marcos 貢獻此圖。
示例:
輸入: [0,1,0,2,1,0,1,3,2,1,2,1]
輸出: 6
答案參考:
/**
* @param {number[]} height
* @return {number}
*/
var trap = function (height) {
let left = 0, right = height.length - 1
let count = 0
let leftMax = 0, rightMax = 0
while (left <= right) {
leftMax = Math.max(leftMax, height[left])
rightMax = Math.max(rightMax, height[right])
if (leftMax < rightMax) {
count += leftMax - height[left]
left++
} else {
count += rightMax - height[right]
right--
}
}
return count
};