Skip to content
BytePatterns

Container With Most Water

Arrays: lesson 7 of 8

The shorter wall decides. So move the shorter wall.

Lesson 7 of 8 · 6 min

Container With Most Water

Step 1 of 10

Water between two walls is width × the shorter wall. Start as wide as the row allows.

The Idea

Given a row of wall heights, the water between two walls is the width times the shorter height. Start at the widest pair and always move the shorter wall inward. Moving the taller one can only lose area, so skipping it is safe.

Real-World Example

Hanging a rain tarp between two fence posts works the same way. The lower post decides how much water the tarp can hold, so raising the taller post changes nothing. You replace the short one.

The Code

def max_area(height):
    left, right = 0, len(height) - 1
    best = 0
    while left < right:
        h = min(height[left], height[right])
        best = max(best, h * (right - left))
        if height[left] < height[right]:
            left += 1        # only the shorter wall can help
        else:
            right -= 1
    return best

print(max_area([1, 8, 6, 2, 5, 4, 8, 3, 7]))   # 49

Your turn

Fill in the blank.

height = [4, 2, 7]
left, right = 0, 2
# water = width * the shorter wall
area = (right - left) * ___(height[left], height[right])

Mini quiz

1 / 3

The water held between two walls equals: