1. Area = shorter x width
Water is bounded by the shorter wall times the distance.
const area = Math.min(height[left], height[right]) * (right - left)Typorithm · medium
Step 1 of 8 · intro card
Two Pointers
Width starts maximal; move whichever wall is shorter inward, since only a taller wall can ever beat the current area.
The water held by two walls is the shorter height times the distance between them.
Start with the widest container and shrink width by moving a pointer inward.
Always move the shorter wall — keeping it could never increase area, while a new taller wall might.
Area = min(height) x width.
Start at maximum width.
Move the shorter wall inward.
function maxArea(height) {
let left = 0;
let right = height.length - 1;
let best = 0;
while (left < right) {
const area = Math.min(height[left], height[right]) * (right - left);
best = Math.max(best, area);
if (height[left] < height[right]) {
left += 1;
} else {
right -= 1;
}
}
return best;
}Connect each part of the code to the concept before you type.
Water is bounded by the shorter wall times the distance.
const area = Math.min(height[left], height[right]) * (right - left)Keep the largest area seen.
best = Math.max(best, area)Moving the taller wall can only shrink width and area, so move the shorter.
if (height[left] < height[right]) {
left += 1;
}Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.