What is Container With Most Water
Each height[i] is a vertical line at x = i. Two lines form a container whose width is the distance between them and whose water stops at the shorter line. Return the largest area. Checking every pair is too slow on the large test.
1 8 6 2 5 4 8 3 7 49
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each step moves one pointer, and they meet once. |
| Memory | O(1) | Only the two pointers and the best area are stored. |
Implementation
def max_area(h):
l, r, best = 0, len(h) - 1, 0
while l < r:
best = max(best, (r - l) * min(h[l], h[r]))
if h[l] <= h[r]:
l += 1
else:
r -= 1
return best