Container With Most Water
Pick two lines that hold the most water: area = min(height) × width. Start with the widest pair and always move the shorter line inward, since keeping it can never produce a bigger area.
▶ Watch the animated traceTraced input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7] → 49. Original problem: neetcode.io/problems/max-water-container
Complexity
BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)
Each step discards one line.
Key idea
- The shorter line limits the area. Any container that keeps it and is narrower is strictly worse.
- So moving the shorter pointer is the only move that might find a bigger area.
- Track the best area seen along the way.
Common mistakes
- Moving the taller line can only lose area.
- Checking every pair is O(n²) and times out.
- Width is
r - l, notr - l + 1.
Solution
Java
int maxArea(int[] height) {
int l = 0, r = height.length - 1, best = 0;
while (l < r) {
int area = Math.min(height[l], height[r]) * (r - l);
best = Math.max(best, area);
if (height[l] < height[r]) l++;
else r--;
}
return best;
}Python
def maxArea(height: List[int]) -> int:
l, r, best = 0, len(height) - 1, 0
while l < r:
area = min(height[l], height[r]) * (r - l)
best = max(best, area)
if height[l] < height[r]: l += 1
else: r -= 1
return bestC++
int maxArea(vector<int>& height) {
int l = 0, r = (int)height.size() - 1, best = 0;
while (l < r) {
int area = min(height[l], height[r]) * (r - l);
best = max(best, area);
if (height[l] < height[r]) l++;
else r--;
}
return best;
}Edge cases
Each one has its own trace in the interactive view.
| Case | Input | Answer |
|---|---|---|
| Two lines One pair, width 1. | height = [1, 1] | 1 |
| Equal heights The widest pair wins. | height = [4, 4, 4, 4] | 12 |
| Increasing heights Best is 2 × 3 or 3 × 2. | height = [1, 2, 3, 4, 5] | 6 |
| Zero heights Every pair includes a line of height 0, so nothing is held. | height = [0, 2, 0] | 0 |