Q12: How do you solve Container With Most Water using Two Pointers?
Given $n$ vertical lines, find two lines that form a container storing the most water. Initialize pointers at both ends (left = 0, right = len - 1). Calculate area: $text{width} times min(text{height}[left], text{height}[right])$. Move the pointer pointing to the shorter line inward, as moving the taller line can never yield a larger area.
Container With Most Water Solution
public class ContainerWithMostWater {
public static int maxArea(int[] height) {
int maxWater = 0;
int left = 0, right = height.length - 1;
while (left < right) {
int h = Math.min(height[left], height[right]);
int w = right - left;
maxWater = Math.max(maxWater, h * w);
if (height[left] < height[right]) left++;
else right--;
}
return maxWater;
}
}💡 Shrinks container width while attempting to discover larger height boundaries.
Key Takeaways
- Two pointers start at array boundaries.
- Move the pointer with the smaller height inward to seek a larger container area.
Knowledge Check
Why is moving the pointer pointing to the taller line guaranteed NOT to increase the container area?