AceYourInterviews
Checking sign-in…

17. Trapping Rain Water

HardFinalize water by established boundary maxima

Each height value describes a bar of width 1. Compute the total amount of rainwater held between the bars after rainfall.

Count water above every position; bars keep their original order.

Example 1

Input

[4,2,0,3,2,5]

Output

9

Explanation: Per-index volumes are [0,2,4,1,2,0].

Example 2

Input

[3,0,3]

Output

3

Explanation: The middle unit-width cell holds three units.

Constraints

  • 1 <= height.length <= 2 * 104
  • 0 <= height[i] <= 105
  • Each bar has width 1. Return the total trapped water.
Hints
Hint 1

Write the per-index formula using left and right maxima.

Hint 2

If an established left wall is lower than an established right wall, which side can be finalized?

Hint 3

Process the smaller established maximum, update it, and add its difference from the chosen bar.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Finalize cells against established walls

[4,2,0,3,2,5]
9