Widest Water Tank

MediumTwo Pointers≈ 30 min

You are given a list heights of wall heights standing in a row, one step apart. Choose two walls: together with the ground they form a tank, and the water in it rises to the height of the lower of the two walls.

Return the largest amount of water any two walls can hold, measured as lower height × distance between the walls. The walls in between do not get in the way.

Examples

text
heights = [3, 7, 2, 5, 8, 4, 6]   →  30
heights = [2, 2]                  →  2
heights = [5, 1, 1, 1, 5]         →  20

In the first example, the walls at indices 1 and 6 have heights 7 and 6, five steps apart: 6 × 5 = 30.

Constraints

  • Between 2 and 10,000 walls, each between 0 and 10,000 high.
  • Aim for O(n): there are about n² / 2 pairs, and you should not look at all of them.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 3 visible cases here, in your browser. Submit runs all 6 on the judge, 3 of them hidden, and measures how your solution scales.