Problem
Table: Heights
|
|
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 inany order.
The result format is in the following example.
Examples
Example 1:
|
|
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
Method 1 – Prefix Max and Suffix Max Aggregation
Intuition
To calculate trapped rainwater, for each bar, the water above it is determined by the minimum of the maximum heights to its left and right, minus its own height. In SQL, we can use window functions to compute prefix and suffix maximums for each bar.
Approach
- For each row, compute:
left_max
: the maximum height from the start up to the current bar (inclusive).right_max
: the maximum height from the current bar to the end (inclusive).
- For each bar, calculate the trapped water as
GREATEST(LEAST(left_max, right_max) - height, 0)
. - Sum the trapped water for all bars to get the total.
Code
|
|
Complexity
- ⏰ Time complexity: O(n) — n is the number of bars (single scan with window functions).
- 🧺 Space complexity: O(n) — For window function buffers.