Trapping Rain Water in TypeScript

function trap(height: number[]): number {
    let totalWater = 0;
    const n = height.length;

    if (n === 0) {
        return totalWater;
    }

    // Arrays to store the maximum height of bars to the left and right of each bar
    const leftMax: number[] = new Array(n);
    const rightMax: number[] = new Array(n);

    // Fill the leftMax array
    leftMax[0] = height[0];
    for (let i = 1; i < n; i++) {
        leftMax[i] = Math.max(leftMax[i - 1], height[i]);
    }

    // Fill the rightMax array
    rightMax[n - 1] = height[n - 1];
    for (let i = n - 2; i >= 0; i--) {
        rightMax[i] = Math.max(rightMax[i + 1], height[i]);
    }

    // Calculate total trapped rainwater
    for (let i = 0; i < n; i++) {
        totalWater += Math.min(leftMax[i], rightMax[i]) - height[i];
    }

    return totalWater;
}

PrevNext