Container With Most Water
Problem (restated)
You are given height bars on a line. Choose two lines that form a container with the x-axis holding the most water. Return that maximum area.
Intuition
Area = min(h[l],h[r]) * (r-l). Starting at both ends maximizes width; the only way to improve is to move the shorter line inward hoping for a taller height.
Approaches
Two pointers from both ends
Tested onlyIdea. left=0, right=n-1. Track max area. Move the pointer at the shorter height. Stop when left≥right.
Walkthrough. Heights [1,8,6,2,5,4,8,3,7]: start width 8, area min(1,7)*8=8; move left to 8, … eventually best=49.
Trade-offs. Greedy correctness relies on: moving the taller line cannot increase min height and only decreases width.
export function maxArea(height: number[]): number {
let left = 0, right = height.length - 1, best = 0;
while (left < right) {
const h = Math.min(height[left]!, height[right]!);
best = Math.max(best, h * (right - left));
if (height[left]! < height[right]!) left++;
else right--;
}
return best;
}
export function maxArea(height: number[]): number {
let left = 0, right = height.length - 1, best = 0;
while (left < right) {
const h = Math.min(height[left]!, height[right]!);
best = Math.max(best, h * (right - left));
if (height[left]! < height[right]!) left++;
else right--;
}
return best;
}
Try all pairs
Tested onlyIdea. Compute area for every (i,j).
Walkthrough. Nested loops; keep maximum.
Trade-offs. Obvious correctness, fails larger constraints.
export function maxAreaBrute(height: number[]): number {
let best = 0;
for (let i = 0; i < height.length; i++)
for (let j = i + 1; j < height.length; j++)
best = Math.max(best, Math.min(height[i]!, height[j]!) * (j - i));
return best;
}
export function maxAreaBrute(height: number[]): number {
let best = 0;
for (let i = 0; i < height.length; i++)
for (let j = i + 1; j < height.length; j++)
best = Math.max(best, Math.min(height[i]!, height[j]!) * (j - i));
return best;
}
Template connection
Opposite-ends two pointers; move the side that limits the height.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What input would break a careless off-by-one in your window/pointer logic?