100 XP

79. Container with the most water

Advanced two pointers greedy

A row of upright walls stands along a line, one wall at each position 0, 1, 2, ...; heights[i] is the height of the wall at position i. Any two walls, with the ground between them, make a container. The water it holds is its width (the distance between the two walls) times the height of the shorter wall: any higher and the water would spill over it. The walls in between don't get in the way.

Write a function most_water(heights) that returns the most water any two walls can hold. With fewer than two walls there is no container, so the answer is 0.

Trying every pair takes about n * n / 2 steps. Two pointers can do it in one pass, if you can see which wall to give up on at each step.

Example 1

Inputheights = [3, 1, 2, 4, 5]
Output12
ExplanationWalls 0 and 4: width 4 times height 3.

Example 2

Inputheights = [4, 3, 2, 1, 4]
Output16
ExplanationThe two 4s at the ends: width 4, height 4.

Example 3

Inputheights = [1, 1]
Output1
ExplanationWidth 1 times height 1.

Constraints

  • heights has 0 to 500 whole numbers, each from 0 to 10,000.

Submit also runs 9 more tests you can't see.

Code
def most_water(heights):
    """Find the most water two walls can hold.

    heights: list of int, one wall height per position
    Returns: int, the largest (distance between two walls)
        times (the shorter wall's height)
    """
    # Write your code here
    pass