Practice · Two pointers · 2 of 5

Most Water Between Two Walls

You are given a list height of n non-negative integers. Picture a vertical wall at each position i, height[i] units tall, with neighbouring walls one unit apart.

Choose two walls. With the ground they form a tank: its width is the distance between the two walls, and the water can rise only as high as the shorter of them. The walls in between don't get in the way. Return the most water (width × the shorter height) that any pair of walls can hold.

Example 1

Input
height = [2, 7, 4, 8, 3, 6]
Output
24
The walls at positions 1 and 5 are 4 apart, and the shorter is 6 tall: 4 × 6 = 24.

Example 2

Input
height = [1, 1]
Output
1
The only pair: width 1, height 1.

Constraints

  • height holds 2 to 10⁵ numbers.
  • Every height is between 0 and 10⁴.