Skip to content
GKgkml.dev
← Problem set
#11MediumTwo pointers

Container With Most Water

The tell: Maximise an area defined by a pair of positions and the smaller of two heights.

How you get there

  1. 1Area is width × min(left height, right height).
  2. 2Start at the widest pair, since width is maximal there.
  3. 3Moving the taller side can never help — only raising the limiting height can, so move the shorter one.

Solution

Python
def max_area(height: list[int]) -> int:
    lo, hi = 0, len(height) - 1
    best = 0
    while lo < hi:
        best = max(best, (hi - lo) * min(height[lo], height[hi]))
        if height[lo] < height[hi]:
            lo += 1
        else:
            hi -= 1
    return best
Time
O(n)
Space
O(1)

What goes wrong

Moving whichever side you like breaks the proof — it must be the shorter one.