deno.land / x / masx200_leetcode_test@10.6.5 / trapping-rain-water / index.ts
1234567891011121314151617181920212223242526export default trap;function trap(height: number[]): number { const n = height.length; if (n == 0) { return 0; }
const leftMax: number[] = new Array(n).fill(0); leftMax[0] = height[0]; for (let i = 1; i < n; ++i) { leftMax[i] = Math.max(leftMax[i - 1], height[i]); }
const rightMax: number[] = new Array(n).fill(0); rightMax[n - 1] = height[n - 1]; for (let i = n - 2; i >= 0; --i) { rightMax[i] = Math.max(rightMax[i + 1], height[i]); }
let ans = 0; for (let i = 0; i < n; ++i) { ans += Math.min(leftMax[i], rightMax[i]) - height[i]; } return ans;}
Version Info