Skip to main content
CodeOath
← All problems

Problem

Container With Most Water

Medium
  • arrays
  • two-pointers

height[i] is the height of a vertical line standing at position i on the x-axis. Pick any two of these lines. Those two lines and the x-axis enclose a container. Its width is the distance between the two positions, and the water can only rise to the height of the shorter line. Any lines standing between the two make no difference.

Return the greatest area of water that any pair of lines can hold.

Example 1
Input
height = [3, 9, 2, 6, 5, 8, 1]
Output
32
Explanation

the lines at positions 1 and 5 have heights 9 and 8. The width is 4 and the water level is 8, the shorter height, so the area is 32.

Example 2
Input
height = [5, 1, 1, 1, 5]
Output
20
Explanation

the two outer lines are 4 apart and both have height 5, so the area is 20. The short lines between them do not matter.

Constraints:

  • 2 <= height.length <= 10^5
  • 0 <= height[i] <= 10^4

Follow-up: checking every pair takes O(n^2). Can you find the answer in O(n)?

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.