var trap = function (items) { let peakIndex = 0 let maxVal = -1 for (let i = 0; i < items.length; ++i) { if (items[i] > maxVal) { maxVal = items[i] peakIndex = i } }
let sum = 0 { let left = 0 let right = left while (right <= peakIndex) { while (right + 1 <= peakIndex && items[right + 1] < items[left]) { ++right } ++right const curHeight = Math.min(items[left], items[right]) for (let i = left + 1; i < right; ++i) { sum += curHeight - items[i] } left = right } } { let right = items.length - 1 let left = right while (left >= peakIndex) { while (left - 1 >= peakIndex && items[left - 1] < items[right]) { --left } --left const curHeight = Math.min(items[left], items[right]) for (let i = left + 1; i < right; ++i) { sum += curHeight - items[i] } right = left } } return sum }