LeetCode #11
Container With Most Water
This $O(n)$ solution is not intuitional. I proved recursively.
Proof
Let $K(i,j)$ be the water volume between $i$th line and $j$th line, $V(i,j)$be the largest water volume between $i$th line and $j$th line, and $a(i)$ be the height of the $i$th line.
$$V(i,j) = \max(K(i,j), V(i+1,j),V(i,j-1)$$I want to delete either the second term or the third term since this calculation takes $O(n^2)$.
Assume that $a(i)\ge a(j)$,
$$V(i,j) = \max(K(i,j), V(i,j-1))$$Proof.
Let $k,l$ be the lines which have most water between $i+1$th line and $j$th line.
Pattern 1. $(k,l)$ is included in $(i+1, j-1)$
Since $(i+1, j-1$) is included in $(i,j-1)$,$V(i,j-1)\ge V(i+1,j)$.Pattern 2. $(k,l)$ is not included in $(i+1, j-1)$, which means that $l =j$
$a(i)\ge a(j) \Rarr K(i,j) \ge K(k,j) \Rarr K(i,j)\ge V(i+1,j)$.
Therefore, the second term can be deleted.
$$\begin{aligned} V(i,j) &= \max(K(i,j), V(i+1,j),V(i,j-1)) \\ &= \max(K(i,j), V(i,j-1)) \end{aligned}$$This takes at most $O(n)$.
Q.E.D.
Nice proof this directly leads to the two pointer idea.
Key intuition: the area is limited by the shorter line, so move the smaller height pointer inward. That’s why it works in O(n).
Same idea applies in builds too focus on the real constraint and cut the rest. Even in a small
tool hub
keeping things simple made the biggest difference