Pick two walls that hold the most water. Start at both ends and always move the shorter wall inward, since it caps the area.
▼The problem
LeetCode 11 (Medium). Given the heights of n vertical lines, pick two that, with the x-axis, hold the most water. The water rises only to the shorter line, so the area is min(h[i], h[j]) × (j − i). Return the largest area.
Example: [1, 8, 6, 2, 5, 4, 8, 3, 7] → 49 (the 8 at index 1 and the 7 at index 8: 7 high, 7 apart).
def maxArea(height):
left, right = 0, len(height) - 1
best = 0
while left < right:
area = min(height[left], height[right]) * (right - left)
best = max(best, area)
if height[left] < height[right]:
left += 1
else:
right -= 1
return bestTRY IT ON LEETCODE ▶The solution
def maxArea(height):
left, right = 0, len(height) - 1
best = 0
while left < right:
area = min(height[left], height[right]) * (right - left)
best = max(best, area)
if height[left] < height[right]:
left += 1
else:
right -= 1
return bestTranscript
Container With Most Water. You get a row of vertical lines, each with a height. Pick any two, and they hold water between them. But the water can only rise to the shorter line, or it spills over. So the area is the shorter height times the distance between them. Find the biggest area.
Here are nine lines: one, eight, six, two, five, four, eight, three, seven. The best pair is the eight at index one and the seven at the end. Seven high, seven apart: forty-nine.
The simple way tries every pair. Nine lines make thirty-six pairs. A thousand lines make about half a million. That's order n squared, too slow for big inputs.
Better: start with the two outer lines, the widest container there is. Every step inward makes it narrower, so only a taller line can win. Which side should move? Look at the shorter one. Every container it could still make is narrower, and still capped at its own height. It can never beat what we just measured. So drop the shorter line, and step inward.
Let's run it. One and seven, eight apart: area eight. The one is shorter, so the left moves in. Eight and seven, seven apart: forty-nine, a new best. Now the seven is shorter, so the right moves. Eight and three make eighteen. Eight and eight tie at forty; either can move, so the right goes. Then sixteen, fifteen, four and six. The pointers meet. The best was forty-nine.
In code: a left pointer, a right pointer, and a best of zero. While they haven't met, compute the area, the smaller height times the gap, and keep the best. Then move whichever side is shorter. On a tie, the right one moves. Finally, return the best.
Each step moves one pointer one line inward, so they meet after n minus one steps: eight here. That's one pass, linear time. And it keeps just three numbers: constant space.
Start wide, drop the shorter line, keep the best. That's Container With Most Water.