Leetcode - 42. Trapping Rain Water

Rakesh Reddy Peddamallu - Feb 24 - - Dev Community

Mathematical function
Image description
Javascript code

/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function (height) {

    let l = 0;
    let r = height.length - 1;
    let maxLeft = height[l];
    let maxRight = height[r];

    let rainWater = 0;

    while (l < r) {
        if (maxLeft <= maxRight) {
            l++;
            maxLeft = Math.max(maxLeft, height[l]);
            rainWater += maxLeft - height[l];
        } else {
            r--;
            maxRight = Math.max(maxRight, height[r]);
            rainWater += maxRight - height[r];
        }
    }
    return rainWater
};
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .