Hard Dynamic Programming

Trapping Rain Water

Receives an array of non-negative integers representing an elevation map with unit-width bars, and returns the total volume of rainwater trapped between them after it rains. It solves this with bottom-up dynamic programming over two auxiliary arrays: leftMax[i] and rightMax[i] record the tallest bar seen so far scanning from the left and from the right respectively. The water level standing at each index is capped by its shorter bounding wall — min(leftMax[i], rightMax[i]) — minus the bar's own height there; summing that quantity across every index gives the total. Returns that single integer, the total trapped volume; an empty array returns 0.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References