Container With Most Water

35 min · maxArea()

Two fence posts can trap far more water by standing farther apart — unless one of them is so short that it becomes the leak point. You need the best trade between width and height.

The array height describes vertical lines at positions 0 through height.length - 1. Pick two different positions i and j, with i < j. Their container holds this much water:

min(height[i], height[j]) * (j - i)

Return the largest area any pair can hold.

A few details matter:

  • The shorter line sets the water level.
  • The distance between the positions supplies the width.
  • A zero-height line is allowed, though any pair using it holds zero water.

Constraints

  • 2 <= height.length <= 100_000
  • 0 <= height[i] <= 10_000

Hints

Price the obvious search

Checking every pair is correct. At 100,000 lines, though, that means nearly five billion area calculations.

Start with maximum width

Put one pointer at each end. After measuring that container, the next width must be smaller. Which of the two lines could you replace and still have a chance to gain height?

Retire the shorter line

Moving the taller line inward keeps the same short wall or finds an even shorter one, while width shrinks. Only replacing the shorter line can possibly improve the limiting height.

Follow-up

Can you explain why moving the shorter line never discards a pair that could beat the current best area?

Visible cases

Examples

Example 1

ready
Input
height = [
  1,
  8,
  6,
  2,
  5,
  4,
  8,
  3,
  7
]
Expected
49
Why
the lines of height 8 and 7 are seven positions apart: 7 × 7 = 49

Example 2

ready
Input
height = [
  1,
  2,
  3,
  4,
  5
]
Expected
6
Why
increasing height still has to trade against shrinking width

Example 3

ready
Input
height = [
  4,
  3,
  2,
  1,
  4
]
Expected
16
Why
the two height-4 lines span the full width: 4 × 4 = 16

Interview signal

Asked at

AmazonGoogleBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite