Calculate Trapping Rain Water Problem
#3061
Description
LeetCode Problem 3061.
Table: Heights
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| height | int |
+-------------+------+
id is the primary key (column with unique values) for this table, and it is guaranteed to be in sequential order.
Each row of this table contains an id and height.
Write a solution to calculate the amount of rainwater can be trapped between the bars in the landscape, considering that each bar has a width of 1 unit.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Heights table:
+-----+--------+
| id | height |
+-----+--------+
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 2 |
| 5 | 1 |
| 6 | 0 |
| 7 | 1 |
| 8 | 3 |
| 9 | 2 |
| 10 | 1 |
| 11 | 2 |
| 12 | 1 |
+-----+--------+
Output:
+---------------------+
| total_trapped_water |
+---------------------+
| 6 |
+---------------------+
Explanation:

The elevation map depicted above (in the black section) is graphically represented with the x-axis denoting the id and the y-axis representing the heights [0,1,0,2,1,0,1,3,2,1,2,1]. In this scenario, 6 units of rainwater are trapped within the blue section.
Solution
Approach: Prefix and suffix maximum
Water above a bar is held up by the tallest bar on each side: it rises to min(left_max, right_max) and the bar itself takes up height, so the water over it is min(left_max, right_max) - height, never negative because both maxima include the bar. Compute left_max with a running MAX from the first bar to the current one and right_max from the current one to the last, using explicit window frames, then sum the difference over all bars.
WITH levels AS (
SELECT height,
MAX(height) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS left_max,
MAX(height) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS right_max
FROM Heights
)
SELECT SUM(LEAST(left_max, right_max) - height) AS total_trapped_water
FROM levels;