Skip to content

Latest commit

 

History

History
31 lines (24 loc) · 855 Bytes

File metadata and controls

31 lines (24 loc) · 855 Bytes

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Screen Shot 2021-09-16 at 11 57 41 PM

/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function(height) {
    let lmax = 0, rmax = 0, l = 0, r = height.length - 1;
    let res = 0;
    
    while(l < r) {
        lmax = Math.max(lmax, height[l]);
        if(height[l] < lmax) {
            res += lmax - height[l];
        }
        
        rmax = Math.max(rmax, height[r]);
        if(height[r] < rmax) {
            res += rmax - height[r];
        }
        
        height[l] < height[r] ? l++ : r--;
    }
    return res;
};