DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 42. Trapping Rain Water

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

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay