Container With Most Water

MediumTwo pointers

height[i] is the height of a vertical line drawn at position i. Any two lines, with the ground between them, form a container.

The water it holds is the distance between the two lines times the height of the shorter one. Return the most water any container can hold.

Examples

Example 1
Input:  height = [2, 5, 4, 8, 3, 6]
Output: 20

The lines at indexes 1 and 5, heights 5 and 6, are 4 apart: they hold 5 × 4 = 20.

Example 2
Input:  height = [3, 3]
Output: 3

Two lines of height 3, one apart, hold 3.

Constraints

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

Stuck?

Hint 1

Start with the widest container, the two outer lines. Any narrower one only holds more if its shorter side is taller.

Hint 2

Move inward from whichever side is shorter: keeping that line can never beat the container you have just measured.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur