function trap(height) {let left = 0, right = height.length - 1;◄
let leftMax = 0, rightMax = 0;
let water = 0;
while (left < right) { if (height[left] < height[right]) {leftMax = Math.max(leftMax, height[left]);
water += leftMax - height[left];
left++;
} else {rightMax = Math.max(rightMax, height[right]);
water += rightMax - height[right];
right--;
}
}
return water;
}
Water above a bar is limited by the tallest wall to its left and the tallest to its right: trapped = min(leftMax, rightMax) − height[i].
Use two pointers with running maxima leftMax and rightMax. The clever part: whichever side currently has the SHORTER wall is the binding constraint, so that column’s water is fully determined right now.
If height[left] < height[right], then leftMax is guaranteed ≤ rightMax for the left column, so add leftMax − height[left] and move left inward. Otherwise do the mirror on the right.
This resolves one column per step in a single pass — O(n) time and O(1) space, no prefix arrays needed.