barrett@ruth:~$ /algorithms

Two Pointers

technique overview

container with most water

Sometimes, the mathematical solution is the simplest.

The area of a container bounded by the ground and its columns at positions \((l, r)\) is: \[ \text{area} = \text{width} \cdot \text{length} = (r - l) \cdot \min\{height[l], height[r]\} \]

At its core, this is a maximization problem: maximize the contained area. \[ \max\{(r - l) \cdot \min\{height[l], height[r]\}\} \]

Given a new column position \(l_0 < l\) or \(r_0 < r\), the contained area can only increase if the height of the corresponding column increases.

The following correct solution surveys all containers, initialized with the widest columns positions, that are valid candidates for a potentially new largest area. A running maximizum, the answer, is maintained.

def maxArea(height: list[int]) -> int:
    area = 0
    l, r = 0, len(height) - 1
    while l < r:
        width, min_height = r - l, min(height[l], height[r])
        area = max(area, width * min_height)
        while l < r and height[l] <= min_height:
            l += 1
        while l < r and height[r] <= min_height:
            r -= 1
    return area