Example 1
- Input
- height = [1,8,6,2,5,4,8,3,7]
- Output
- 49
Lines 1 (height 8) and 8 (height 7) give min(8, 7) * (8 - 1) = 49, which is larger than every other pair.
Given an array height where each entry marks the height of a vertical line, choose two lines that with the x-axis hold the most water and return that maximum area. A pair at distance w with shorter height h holds w * h units.
You are given an integer array height of length n. The endpoints of line i are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container holding the most water, and return that maximum amount. The container may not be slanted, so a pair i < j holds min(height[i], height[j]) * (j - i) units.
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4Lines 1 (height 8) and 8 (height 7) give min(8, 7) * (8 - 1) = 49, which is larger than every other pair.
The only pair holds min(1, 1) * 1 = 1.
Every pair includes a zero-height wall, so every container has zero area despite the tall middle line.
All pairs have limiting height 5. The endpoints give the greatest width, 3, and area 5 * 3 = 15; moving either pointer on a tie is safe.
A container is limited by its shorter wall, so its area is width times the smaller height. Example 1 pairs index 1, height 8, with index 8, height 7: width 7 times height 7 gives 49. Begin with the widest pair. As width shrinks, improvement requires a taller limiting wall, so discard the shorter endpoint and keep looking inward. Lines between the endpoints do not subtract from the container area.
Reveal Brute Force: intuition, complexity, and code
[1, 1], where the single pair is the answer.[0, 2, 0], where any pair touching a 0 holds nothing.[5, 5, 5, 5], where the outermost pair wins and either pointer may move on ties.max instead of min, which credits water the shorter wall cannot hold.n = 10^5.When candidates are ordered pairs and one move provably cannot improve the answer, converging pointers from both ends checks only the survivors in linear time.