Core Idea: Pre-compute the maximum heights on the left and right of every position, then calculate water trapped.
Steps:
max_left[] and max_right[], both of size nmax_left[i] = maximum height from index 0 to i
max_left[0] = height[0]max_left[i] = max(max_left[i-1], height[i])max_right[i] = maximum height from index i to end
max_right[n-1] = height[n-1]max_right[i] = max(max_right[i+1], height[i])water_at_i = min(max_left[i], max_right[i]) - height[i]Why it works: You have complete information about what's on both sides of every position before calculating water.
Time: O(n) - three passes Space: O(n) - two arrays
Core Idea: Use two pointers moving from both ends, maintaining running maximums, and only calculate water on the side with the SMALLER maximum.
Key Insight: You don't need to know BOTH max_left and max_right for a position if you know one side's max is definitely smaller. The smaller side is the bottleneck (determines water level), so you can calculate water there immediately.
Steps:
left = 0, right = n-1, left_max = 0, right_max = 0, water = 0left < right:
left_max = max(left_max, height[left])right_max = max(right_max, height[right])left_max vs right_max
left_max < right_max:
left position = left_max - height[left]left++ (we know left side is bottleneck)right position = right_max - height[right]right-- (we know right side is bottleneck)Why it works:
left_max < right_max, you KNOW the water level at position left is determined by left_max (regardless of what's beyond right)