Start learning free

LESSON 350 OF 674 · TWO POINTERS

Container with Most Water

Practice O(n)

You get an array height. Each number is the height of a wall. The walls stand in a row on a flat floor, 1 unit apart.

Pick two walls. Return the largest area of water they can hold.

Two walls and the floor make a container. The water fills it up to the top of the shorter wall. Its area is the distance between the walls times that shorter height.

Note: The walls in between don't block the water. The container can't be tilted. There are always at least 2 walls.

 

2 6 3 5 8 1 4 2 01234567 5 × 4 = 20

The walls of Example 1. The blue area is the most water two walls can hold.

 

Example 1:

Input: height = [2,6,3,5,8,1,4,2]
Output: 20
Explanation: The walls at positions 1 and 6 hold the blue water.
They are 5 apart, and the shorter one is 4 tall: 5 × 4 = 20.
The tallest walls, 6 and 8, are only 3 apart: 3 × 6 = 18.
The two outer walls give 7 × 2 = 14.

Example 2:

Input: height = [5,5]
Output: 5
Explanation: There are only two walls.
They are 1 apart and both 5 tall: 1 × 5 = 5.

Example 3:

Input: height = [0,4,0]
Output: 0
Explanation: Every pair includes a wall of height 0.
So no pair holds any water.

 

Constraints:

  • 2 to 30,000 walls.
  • Each wall is from 0 to 100,000,000 tall.
  • The largest area always fits in a 32-bit signed integer.
STEP 1 OF 7
    Ctrl + Enter to check