Two pointers · Medium
Container With Most Water: the idea to remember.
Choose two vertical lines that hold the most water between them.
The core insight
Evaluate the endpoints and move the shorter line inward.
Why it works
Keeping the shorter line while reducing width cannot improve the area. Discarding it cannot lose a better pair using that endpoint.
The mistake to avoid
Moving the taller endpoint has no justification for discarding candidates.
Time: O(n)Space: O(1)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int maxArea(int[] height) {
int l = 0, r = height.length - 1, best = 0;
while (l < r) {
best = Math.max(best, (r - l) * Math.min(height[l], height[r]));
// The shorter line limits the area.
if (height[l] <= height[r]) l++;
else r--;
}
return best;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.