#11 Container With Most Water

MediumTwo Pointers~20 min

You're given an array height where height[i] is the height of a vertical wall standing at position i on the x-axis. Pick two walls; together with the x-axis they form an open-topped container whose water level is capped by the shorter wall.

Return the largest area of water any pair of walls can hold. That is, the maximum of (j − i) × min(height[i], height[j]) over all pairs i < j. The walls are lines with no thickness, and you can't tilt the water.

Examples

Inputheight = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output49

Walls at indices 1 and 8 (heights 8 and 7): width 7, capped at height 7, area 49. No other pair beats it.

Inputheight = [1, 1]
Output1

Width 1 × min height 1 = 1.

Constraints

  • 2 ≤ height.length ≤ 10⁵
  • 0 ≤ height[i] ≤ 10⁴

The explainer is the good part.

Sign in for the full intuition build-up, every approach from naive to optimal with complexity analysis, progressive hints, and commented solutions in Python, JavaScript, and Java. All free.

Want a taste first? Try a free sample: Two Sum or Valid Parentheses.