Q12: Container With Most Water

Given $n$ non-negative integers representing vertical lines, find two lines that together with the x-axis form a container holding the maximum water.

Two-Pointer Container Area Maximizer
function maxArea(height) {
  let left = 0;
  let right = height.length - 1;
  let maxWater = 0;
  
  while (left < right) {
    const width = right - left;
    const h = Math.min(height[left], height[right]);
    maxWater = Math.max(maxWater, width * h);
    
    if (height[left] < height[right]) left++;
    else right--;
  }
  return maxWater;
}

console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])); // 49
💡 Calculates container area bounded by shorter line. Advances shorter boundary pointer inward since moving the taller pointer could never increase height area.
Key Takeaways
  • Two-pointer approach moving inward from left and right edges.
  • Always advance the pointer holding the shorter height to search for larger area candidates.
Knowledge Check

Why is the shorter pointer moved inward in each iteration step?