Container With Most Water
The problem
Vertical lines stand at consecutive integer x-coordinates with nonnegative heights. Choose two lines that hold the greatest area of water with the x-axis; the water height is the shorter line.
Example
heights = [2, 7, 4, 6] → 12
Need a hint?
Moving the taller side cannot improve the area while the shorter side stays fixed.
Write pseudocode, trace the example, or note an edge case. This scratchpad does not run code.
Notes stay in this browser when storage is available.
Read the solution approach
Start at the two ends and record width × minimum height. Move the pointer at the shorter line inward; on a tie, either side may move. Recompute until the pointers meet. A narrower container can win only by improving its limiting height.
Complexity
O(n) time and O(1) extra space.
Before moving on, explain why the algorithm is correct and trace a boundary case without looking at the approach.