현재 위치에서 왼쪽에 있는 max와 오른쪽에 있는 max를 구하고, 그것의 min을 구하면 현재 위치에서 빗물이 고이는 세로가 된다. 해당 세로를 구한 후, 현재 높이가 세로보다 작을 때 빗물의 총량에 세로-현재높이
를 더해주는 식으로 구현했다.
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let [hw, arr] = fs.readFileSync(filePath).toString().trim().split("\n");
const [h, w] = hw.split(" ").map(Number);
arr = arr.split(" ").map(Number);
let result = 0;
for (let i = 1; i < w; i++) {
let maxleft = Math.max(...arr.slice(0, i));
let maxright = Math.max(...arr.slice(i + 1));
let sero = Math.min(maxleft, maxright);
if (arr[i] < sero) {
result += sero - arr[i];
}
}
console.log(result);