AFFILIATE LINKS
Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard
Here is the full implementation.
/**
* @param {number[]} height
* @return {number}
*/
let trap = function(height) {
if (height === null) {
return 0;
}
let totalWater = 0;
let length = height.length;
let leftMax = [];
let rightMax = [];
leftMax[0] = height[0];
for (let i = 1; i < length; i++) {
leftMax[i] = Math.max(height[i], leftMax[i - 1]);
}
rightMax[length - 1] = height[length - 1];
for (let i = length - 2; i >= 0; i--) {
rightMax[i] = Math.max(height[i], rightMax[i + 1])
}
for (let i = 1; i < length - 1; i++) {
totalWater += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return totalWater;
};