AceYourInterviews
Checking sign-in…

16. Container With Most Water

IntermediateTwo-pointer elimination

Choose two vertical lines to form the sides of a container, with the horizontal axis as its base. Its width is the distance between the indices, and its usable height is the shorter of the two chosen lines.

Maximize width multiplied by usable height. Lines cannot be tilted or reordered, and the answer is an area rather than the sum of the two heights.

Example 1

Input

[1,8,6,2,5,4,8,3,7]

Output

49

Explanation: Choose indices 1 and 8, whose heights are 8 and 7. Their horizontal distance is 8 - 1 = 7, and water can rise only to the shorter height, 7. The area is therefore 7 × 7 = 49; no other pair encloses a greater area.

Example 2

Input

[1,1]

Output

1

Explanation: Width one times height one.

Example 3

Input

[1000000000,0,0,1000000000]

Output

3000000000

Explanation: Cast before multiplication to retain the full area.

Constraints

  • 0 <= height.length <= 105
  • 0 <= height[i] <= 109
Hints
Hint 1

Can a smaller width help if the limiting height stays the same?

Hint 2

Fix the shorter boundary and compare it with all interior partners.

Hint 3

Record the area and move the shorter side inward.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Move the limiting boundary

[1,2,4,3]
4