Given n non-negative bar heights of width 1, compute how much rain water is trapped between the bars after raining.
Move inward from both ends, always on the side with the lower max. That side's water is bounded by its own max, since the other side is known to be at least as tall.
1function trap(height: number[]): number {2let l = 0, r = height.length - 1, lMax = 0, rMax = 0, water = 0;3while (l < r) {4lMax = Math.max(lMax, height[l]); rMax = Math.max(rMax, height[r]);5if (lMax < rMax) water += lMax - height[l++];6else water += rMax - height[r--];7}8return water;9}
Pointers at both ends.
Space: play/pause · ←/→: step