Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
주어진 배열이 각 블럭의 높이라고 했을 때, 빗물이 가둬진 칸의 갯수를 구하는 문제이다.
var trap = function(height) {
let result = 0;
let left = 0;
let right = height.length-1;
const maxHeight = Math.max(...height)
const maxHeightIdx = height.indexOf(maxHeight);
let leftMax = 0;
let rightMax = 0;
while(left < maxHeightIdx) {
leftMax = height[left] > leftMax ? height[left] : leftMax;
result += leftMax - height[left]
left++
}
while(right > maxHeightIdx) {
rightMax = height[right] > rightMax ? height[right] : rightMax;
result += rightMax - height[right]
right--
}
return result;
};