Container With Most Water
Problem
height[i] is the height of a vertical wall standing at x-position
i. Pick two walls; together with the x-axis they form a container whose water
level is limited by the shorter wall. Return the largest amount of water any pair can
hold, i.e. max of min(h[i], h[j]) × (j - i).[1,8,6,2,5,4,8,3,7]Output49[1,1]Output12 ≤ n ≤ 105 · 0 ≤ height[i] ≤ 104
Try it yourself
class Solution {
public int maxArea(int[] height) {
}
}
Instinct Sorted input, a pair/triple hitting a target, or something symmetric? Put one pointer at each end and move the one that can only improve things.
Memory hack Squeeze from both ends - every step throws away a whole row of the brute-force grid.
Open the Two Pointers guide →Approaches
Brute ForceTry Every Pair of Walls
O(n2)Space O(1)For every pair i < j, the water is
min(height[i], height[j]) * (j - i). Track the maximum over all
n(n-1)/2 pairs.
public int maxArea(int[] height) { int maxArea = 0; for (int i = 0; i < height.length; i++) { for (int j = i + 1; j < height.length; j++) { int area = Math.min(height[i], height[j]) * (j - i); maxArea = Math.max(maxArea, area); } } return maxArea; }
Direct translation of the definition — times out for n = 105.
OptimalTwo Pointers — Move the Shorter Wall
O(n)Space O(1)Put left at 0 and right at n-1, record the area, then
move whichever pointer has the shorter wall. Every pair skipped this way contains
that shorter wall with a smaller width, so its area is ≤ the one just recorded
— the optimum is never lost.
public int maxArea(int[] height) { int maxArea = 0; int left = 0, right = height.length - 1; while (left < right) { int area = Math.min(height[left], height[right]) * (right - left); maxArea = Math.max(maxArea, area); if (height[left] < height[right]) left++; // shorter wall can't improve else right--; } return maxArea; }
Dry run[1,8,6,2,5,4,8,3,7]
- 11l86254837rmin(1,7)×8=8 → l++
- 218l6254837rmin(8,7)×7=49 → r--
- 318l625483r7min(8,3)×6=18 → r--
- 418l62548r37min(8,8)×5=40 → r--
- …18l6r254837all smaller → max=49 ✔
One pass, constant space; the greedy discard is provably safe.
At a glance
| Level | Approach | Time | Space |
|---|---|---|---|
| Brute Force | Try Every Pair of Walls | O(n2) | O(1) |
| Optimal | Two Pointers — Move the Shorter Wall | O(n) | O(1) |
- Moving the taller wall — can skip the optimal pair.
- Confusing with Trapping Rain Water: here only two walls matter, inner walls are ignored.
- Using
maxinstead ofminof the heights for the water level.
- Give the brute force, then ask “which pairs can I rule out?”
- Prove the greedy step: width shrinks, height is capped by the short wall.
- On ties, moving either pointer is fine — mention it.