Given an integer array height where height[i] is the height of a vertical line at position i, find two lines that, together with the x-axis, form the container holding the most water. Return that maximum area.
Example
Input height = [1,8,6,2,5,4,8,3,7]
Output 49
Key Pointers
The water held between two lines is capped by the shorter one — area = min(height[l], height[r]) * (r - l).
Starting at the widest possible container (both ends) and moving the shorter pointer inward is the only move that can ever increase the area; moving the taller pointer inward can only shrink width without ever gaining height.
Track the best area seen at every step, since narrowing the window always shrinks width even on the steps where height improves.
Step-by-Step Analysis
Set left = 0, right = len(height) - 1, and best = 0.
While left < right: compute area = min(height[left], height[right]) * (right - left), and update best if it's larger.
Move whichever pointer points at the shorter line inward — if height[left] < height[right], advance left; otherwise pull right back.
Repeat until the pointers meet; return best.
Complexity
Time: O(n) — Space: O(1)
Code
def maxArea(height: list[int]) -> int:
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 best
Code Explanation
How the solution above works, piece by piece.
Start with the widest container: left = 0, right = n − 1.
area = min(height[left], height[right]) * (right - left): water is limited by the shorter wall.
Keep the best area seen.
Move the pointer at the shorter wall. Any container that keeps that wall and is narrower can't be better, so it's safe to discard.
One pass, each step drops one wall: O(n) time, O(1) space, instead of trying all O(n²) pairs.
Visual Walkthrough
Running it on height = [1, 8, 6, 2, 5, 4, 8, 3, 7]:
Area = shorter wall × distance. Each step moves the shorter wall inward, because moving the taller one can only shrink the width without raising the limiting height. The best pair is index 1 and 8: min(8, 7) × 7 = 49.