Container With Most Water
Difficulty: Medium
You're given the heights of a row of vertical lines, spaced one unit apart. Any two lines, with the ground between them, form a container. Its height is the shorter of the two lines (water spills over the shorter side), and its width is the distance between them.
Return the most water any container can hold.
Examples
Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output: 49
Picking the lines of height 8 (index 1) and height 7 (index 8) gives a width of 7 and a wall height of min(8, 7) = 7, for an area of 49 — the best possible.
Input: height = [1, 1]
Output: 1
There's only one pair to choose, giving min(1, 1) * 1 = 1.
Input: height = [4, 3, 2, 1, 4]
Output: 16
The two outer lines, both height 4, give min(4, 4) * 4 = 16.
Constraints
2 <= height.length <= 10^5
0 <= height[i] <= 10^4
Approach
The direct approach checks every pair of lines and keeps the best area. It's correct but repeats a lot of work.
A faster approach starts two pointers at the ends, the widest container. At each step, compute the area, then move the pointer on the shorter line inward. Moving the taller line can't help: the width shrinks and the shorter line still limits the height. Only moving the shorter line can find a taller wall and a bigger area, so one pass is enough.
Solutions
Brute Force — Check Every Pair
Compute the area for every possible pair of lines, and keep track of the largest one seen.
function maxArea(height) {
let best = 0;
for (let i = 0; i < height.length; i++) {
for (let j = i + 1; j < height.length; j++) {
const area = Math.min(height[i], height[j]) * (j - i);
best = Math.max(best, area);
}
}
return best;
}Time: O(n²) · Space: O(1)
Optimal — Two Pointers
Start with a pointer at each end, the widest container. At each step, record the area, then move the pointer on the shorter line inward. That's the only move that can improve the area.
function maxArea(height) {
let left = 0;
let right = height.length - 1;
let best = 0;
while (left < right) {
const width = right - left;
const shortest = Math.min(height[left], height[right]);
best = Math.max(best, shortest * width);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}Time: O(n) · Space: O(1)