79. Container with the most water
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
heights = [3, 1, 2, 4, 5]12Example 2
heights = [4, 3, 2, 1, 4]16Example 3
heights = [1, 1]1Constraints
heightshas 0 to 500 whole numbers, each from 0 to 10,000.
Submit also runs 9 more tests you can't see.
- Start with the widest container: the walls at the two ends,
i = 0andj = len(heights) - 1. Work out its water and keep the best. - Then move one end inward. Moving the taller wall can't help: the container gets narrower, and the shorter wall still limits the height.
- So always move the shorter wall (either one when they are equal), and stop when the two ends meet.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.