Lines of the given heights stand at each index. Choose two that, with the x-axis, form a container holding the most water, and return that amount.
Before you code
Area is width times the shorter height. Starting from the widest pair, the only move that could find a bigger area is to discard the shorter line.
Hints
- Start with the two ends and compute the area.
- Move the pointer at the shorter line inward; on a tie, either.
- Track the maximum. O(n) time.
Production & complexity notes
When solving Container with most water on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Two pointers to reinforce the underlying pattern.
What it practices
Discarding the limiting element, from Two pointers.