42. Trapping Rain Water
Intitution
To trap water between the bars, we need to know the maximum height to the left and to the right of each bar.
The water that a bar can trap =
min(leftMax, rightMax) - heightAtBar
, as long as this value is positive.
We traverse twice:
Right to left to build an array of right max heights.
Left to right to calculate trapped water using current height and right max.
Complexity
Space Complexity
Time Complexity
Code
Last updated