Maintained by Vikas Dulgunde, software engineer
Picture a row of upright sticks standing on a number line. The stick at position i rises to height[i]. If you choose any two sticks, water can sit in the rectangle they bound. The width of that rectangle is the gap between the two positions, and the depth is limited by the shorter of the two sticks, because anything taller would simply spill over the lower side.
Your task is to try every possible pairing in spirit and report the single largest area. The area for a pair at indices i and j is (j - i) multiplied by the smaller of height[i] and height[j].
The container has straight vertical walls and a flat floor, so you cannot tilt it to scoop more. Only the two chosen sticks and the ground beneath them matter; sticks in between are ignored and do not block the water.
The stick of height 8 at index 1 and the stick of height 7 at index 8 are 7 apart. Depth is capped at the shorter wall, 7, so the area is 7 * 7 = 49. No other pair beats this.
Only one pair exists. Width 1 times the shorter height 1 gives 1.
The two 4s sit at the far ends, 4 apart. The shorter wall is 4, so 4 * 4 = 16, the best you can do here.
Visible test cases
The area of any pair depends on two things that pull against each other: a wider gap raises the width, but the depth is always pinned to whichever wall is shorter.
Start with the widest possible gap, one pointer at each end, then ask which move could ever improve things.
Moving the pointer at the taller wall inward can only shrink the width while keeping the same height cap, so it can never help. Always advance the pointer sitting at the shorter wall.
Compute the area for every pair of indices and keep the maximum. Correct but slow because it re-examines pairs that cannot win.
Begin with the widest container and shrink it intelligently. The depth is set by the shorter wall, so abandoning the taller wall can never recover the lost width. Move the shorter wall inward each step, hoping to find a taller one.