Two pointers from the outside in
Measure the current container, then move the pointer at the shorter wall inward.
Widest first. At each step compute the area, keep the best, and retire the shorter wall — it can never be part of a better container.
Algorithm
l = 0,r = n − 1,best = 0.- While
l < r:area = (r − l) × min(h[l], h[r]),best = max(best, area). - If
h[l] < h[r]thenl += 1, elser −= 1. - Return
best.
- Time
- O(n)
- Space
- O(1)
class Solution: def maxArea(self, height: list[int]) -> int: l, r = 0, len(height) - 1 best = 0 while l < r: area = (r - l) * min(height[l], height[r]) best = max(best, area) if height[l] < height[r]: l += 1 # the left wall can never do better; retire it else: r -= 1 # the right wall can never do better; retire it return best