Loading practice problems…
Loading your practice workspace…
Loading code editor…
6 / 29
Sign in
Algorithms/Two Pointers

Container With Most Water

medium30 min

Each value in heights represents a vertical line at that index. Choose two lines that hold the greatest amount of water.

Return the maximum area. The area is the shorter height multiplied by the distance between the lines.

Example 1

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

Output49

The lines of heights 8 and 7 at indices 1 and 8 form the largest container. Its width is 7 and the shorter line is 7 units tall, so the area is 7 × 7 = 49.

Example 2

Inputheights = [1, 1]

Output1

There is only one pair of lines. Its width and shorter height are both 1, so the area is 1 × 1 = 1.

Constraints

  • 2 ≤ heights.length ≤ 100,000
  • 0 ≤ heights[i] ≤ 10,000
Two PointersGreedy