Given a table Heights containing id and height columns, calculate the amount of rainwater that can be trapped between the bars in the landscape. Each bar has a width of 1 unit.
Problem: For each position, water can be trapped if there are taller bars on both sides. The water level at any position is determined by the minimum of the maximum heights to its left and right, minus the current height.
Table Structure:
id: Sequential position identifier (primary key)height: Height of the bar at that position
Return the total amount of trapped rainwater as a single value.
Table Schema
| Column Name | Type | Description |
|---|---|---|
id
PK
|
int | Sequential position identifier (primary key) |
height
|
int | Height of the bar at that position |
Input & Output
| id | height |
|---|---|
| 1 | 0 |
| 2 | 1 |
| 3 | 0 |
| 4 | 2 |
| 5 | 1 |
| 6 | 0 |
| 7 | 1 |
| 8 | 3 |
| trapped_water |
|---|
| 6 |
Water gets trapped at positions where there are higher bars on both sides. Position 3 (height=0) traps 1 unit between bars at positions 2 and 4. Position 5 (height=1) traps 1 unit, and position 6 (height=0) traps 1 unit. Additional water is trapped at other positions, totaling 6 units.
| id | height |
|---|---|
| 1 | 3 |
| 2 | 2 |
| 3 | 1 |
| 4 | 0 |
| trapped_water |
|---|
| 0 |
This is a decreasing sequence of heights, so no water can be trapped. Water would flow off to the right side, resulting in 0 trapped water.
| id | height |
|---|---|
| 1 | 3 |
| 2 | 0 |
| 3 | 2 |
| trapped_water |
|---|
| 2 |
Position 2 has height 0 and is surrounded by heights 3 and 2. The water level is min(3,2) = 2, so 2 units of water are trapped at position 2.
Constraints
-
1 ≤ number of rows ≤ 20000 -
0 ≤ height ≤ 35000 -
idvalues are sequential and start from 1