Compute trapped water using left max and right max arrays in three passes
For each position i, water trapped equals min(leftMax, rightMax) - height[i]. Computing left max and right max from scratch per index costs O(n) each, totaling O(n²). Precomputing them in separate passes reduces this to O(n) with three independent linear scans.
Water level at any position is bounded by the shorter of the tallest walls on either side. Precomputing these boundaries avoids redundant scans.
lmax: array of n elements storing left maximumsrmax: array of n elements storing right maximumsout: single integer accumulatori: single integerTwo auxiliary arrays of size n store the running maximums from each direction. A two-pointer approach can reduce space to O(1) by computing left and right max on the fly, but the array approach is clearer for visualization and understanding.
The space trade-off is between O(n) with precomputed arrays (simpler logic) and O(1) with two pointers (more complex but space-efficient). Both achieve O(n) time.