/** * @param {number[]}heights * @return {number} */ var trap = function(heights) { var len = heights.length; var res = 0; var max = 0; var leftMaxs = []; var rightMaxs = [];
for (var i = 0; i < len; i++) { leftMaxs[i] = max = Math.max(max, heights[i]); } max = 0; for (var j = len -1; j >= 0; j--) { rightMaxs[j] = max = Math.max(max, heights[j]); }
for (var k = 0; k < len; k++) { res += Math.min(leftMaxs[k], rightMaxs[k]) - heights[k]; }