height[i] is the height of a vertical wall standing at position i on a line. Choose two walls: together with the ground they form a tank, and the water in it can rise only as high as the shorter of the two. Its amount is that height times the distance between the walls.
Return the most water any pair of walls can hold. The tank cannot be tilted.
The walls at positions 1 and 4 (heights 9 and 7) are 3 apart, and the water stops at the shorter one: 7 × 3 = 21.
Constraints
n == height.length2 <= n <= 10⁵0 <= height[i] <= 10⁴Start with the widest tank: the first and last walls. Every other tank is narrower, so it can only win by being taller.
A tank's water is width × height, where the width is the distance between the two walls and the height is the shorter wall. A tall wall next to a short one is wasted: the water spills over the short one.
Time O(n)Space O(1)
The full walkthrough and code are part of Premium
21