LeetCode 42 Trapping Rain Water - Why Naive Fails

The trap

For each position, find the maximum height to its left and right. Water at that position is min(leftMax, rightMax) - height[i].

Finding the maximum on each side takes O(n)O(n) per position. With nn positions, that's O(n2)O(n^2) total.

For n=2×104n = 2 \times 10^4, you'd have 4×1084 \times 10^8 operations. Too slow.