LeetCode42. Rainwater JavaScript

Given na non-negative integer width of each 1column of the height map calculated Click column arrangement, then able to take much rain rain.

The above array is [0,1,0,2,1,0,1,3,2,1,2,1]highly view showing, in this case, can take 6the rain (rain blue part denotes) units. Thank Marcos contribution to this figure.

Example:

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

Reference answer:

/**
 * @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
};

Welcome attention

Guess you like

Origin blog.csdn.net/weixin_40659167/article/details/88314384