/42. Trapping Rain Water

42. Trapping Rain Water

Hard
Arrays66.9% acceptance

Given an array of non-negative integers representing the heights of vertical bars, where each bar has a width of 1, compute the total amount of water that can be trapped between the bars after rainfall. Water can only be trapped between bars if there are taller bars on both sides.

Example 1

Input: [2,0,2]

Output: 2

Explanation: Water trapped between the two bars of height 2 is 2 units.

Example 2

Input: [1,3,2,1,2,1,5,2,2,1,4,2,2]

Output: 12

Explanation: Total water trapped is 12 units.

Constraints

  • 1 <= len(bar_heights) <= 20000
  • 0 <= bar_heights[i] <= 100000 for all valid i
Python (current runtime)

Case 1

Input: [0,2,1,3,0,1,2,1,2,1]

Expected: 5

Case 2

Input: [5,4,1,2]

Expected: 1

Case 3

Input: [3,0,0,2,0,4]

Expected: 10

Case 4

Input: [1,1,1,1]

Expected: 0

Case 5

Input: [0,0,0,0,0]

Expected: 0