medium

Container With Most Water

You are given an array of vertical line heights at unit-spaced positions. Pick two lines so that, together with the x-axis, they enclose the largest possible amount of water. Return that area (width × shorter height).

Constraints
  • 2 ≤ n ≤ 10^5
  • 0 ≤ height[i] ≤ 10^4
Examples
in: height = [1,8,6,2,5,4,8,3,7]
out: 49
Lines at indices 1 and 8 (heights 8 and 7) span width 7.
Recognition clues
  • Answer depends on the pair (width × min height)
  • Starting from the widest span, only moving the *shorter* side can improve
  • Opposite-direction pointers
Pattern
Two Pointers

When order gives you a way to decide which of two ends to move, you can replace an O(n^2) double loop by a single pass. Opposite-direction pointers exploit sortedness (move the side that must change); same-direction pointers maintain a "written so far" prefix for in-place compaction.

Solution

Start with l = 0 and r = n - 1, the widest container. Compute its area and then move whichever pointer has the shorter line inward. Keeping the shorter line while narrowing can never increase the area because the height is capped by it, so discarding it loses no candidate. Continue until the pointers meet and return the maximum area seen.

time O(n)space O(1)
Alternative approaches
  • Brute force over all pairs is O(n^2); no faster exact alternative is needed.
Code it yourself
Solve in
Hints: