Container With Most Water

Another weekend LeetCode problem that's surprisingly elegant. The setup: given vertical lines, find two that hold the most water.

The brute force approach

My first thought was check every pair - O(n²). Works for small inputs but dies on larger ones.

The two-pointer insight

The clever solution uses two pointers at opposite ends. The key idea: always move the shorter line inward.

func maxArea(height []int) int {
    left, right := 0, len(height)-1
    maxArea := 0
    
    for left < right {
        width := right - left
        h := height[left]
        if height[right] < h {
            h = height[right]
        }
        area := h * width
        if area > maxArea {
            maxArea = area
        }
        
        if height[left] < height[right] {
            left++
        } else {
            right--
        }
    }
    
    return maxArea
}

Why this works

If you have two lines and move the taller one inward, width decreases but height doesn't increase - so area can only get smaller or stay same. Only by moving the shorter line might you find a taller line that compensates for the lost width.

What I liked about this problem

It's one of those problems where the solution seems obvious once you see it, but it's not obvious at first. The two-pointer pattern shows up in many other problems too.

Good practice for thinking about greedy strategies and optimization!