Container with most water (two pointers)
Medium TimeO(n) SpaceO(1)
Each value in height is a vertical line at that position. Two lines and the ground between them form a container: its width is the distance between them, and its height is the shorter of the two, because water spills over the lower side. Lines in between are ignored — they do not cut the container up. Return the largest area any pair can hold.
Examples
Example 1
- Input
- height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
- Output
- The 8 at index 1 against the 7 at index 8:
49min(8, 7) × (8 − 1)=7 × 7.
Example 2
- Input
- height = [1, 1]
- Output
1min(1, 1) × (1 − 0)= 1, and there is only the one pair to try.
The Code
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++;
else right--;
}
return best;
}
maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]);Done
More like this
All two pointers examples (9) →- Two sum Walk two pointers inward until the pair sums to the target.
- Reverse array Swap the ends and step inward until the pointers meet.
- Valid palindrome March inward from both ends, comparing as you go.
- 3Sum Fix one number, then two-pointer the rest toward zero.
- Sort colors Three pointers sweep 0s to the front and 2s to the back in one pass.
- Remove duplicates A fast reader and a slow writer compact the array in place.