Practice/Bloomberg/Leetcode 42. Trapping Rain Water
CodingMust
You are given an array representing the elevation profile of a terrain, where each element corresponds to a vertical bar of width 1 positioned consecutively. After rainfall, water will accumulate in the valleys between these bars.
Your task is to calculate the total volume of water that can be trapped between the bars. Water at any position is bounded by the tallest bar to its left and the tallest bar to its right. The water level at a position equals the minimum of these two bounding heights, minus the bar's own height at that position.
Example 1:
` Input: heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] Output: 6 Explanation: The bars form multiple valleys. Water accumulates as follows:
Example 2:
` Input: heights = [4, 2, 0, 3, 2, 5] Output: 9 Explanation: A large valley forms between the first bar (height 4) and last bar (height 5).
Example 3:
Input: heights = [3, 0, 2] Output: 2 Explanation: Water fills the valley at index 1 up to height 2.