Problem 31
Trapping Rain Water
Hard · 30 pts · Array, Two Pointers, Stack
Problem
N bars of width 1 stand next to each other, and bar i has height H[i]. After it rains, water collects in the dips between taller bars. Compute the total number of units of water trapped. The water above a bar is limited by the tallest bar to its left and the tallest bar to its right: the water level there is min(maxLeft, maxRight), and the water above the bar is that level minus the bar's height (or 0 if negative). Precomputing both maximums, or using two pointers from both ends, gives an O(N) solution.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the total trapped water.
Constraints
1 <= N <= 100000; 0 <= H[i] <= 100000
Example input
12 0 1 0 2 1 0 1 3 2 1 2 1
Example output
6
Explanation
For 0 1 0 2 1 0 1 3 2 1 2 1, water collects above index 2 (1 unit), indices 4, 5 and 6 (1 + 2 + 1 units) and index 9 (1 unit). That is 1 + 4 + 1 = 6 units in total.