Container With Most Water
Pattern: Two Pointers (Converging)
How to Identify This Pattern?
When you see these signs in a problem, think Two Pointers:
- You need to maximize an area strictly defined by two boundaries (lines).
- The width is determined by the distance between indices (
right - left). - The height is determined by the shorter of the two lines (
min(height[left], height[right])). - Brute force (checking every pair) is O(n²), but you need O(n).
Pattern Intuition: Area is limited by the shorter line. To potentially get a bigger area, you MUST move the shorter line inward. Moving the taller line inward can never increase area because width decreases and heigh is still limited by the short line.
Optimal Approach
Why Two Pointers Work Here?
- We start with maximum width (pointers at edges).
- At each step, we make a greedy choice: get rid of the standard limiting factor (the shorter line).
- This safely eliminates search space because keeping the shorter line while decreasing width (moving the other pointer) is guaranteed to produce smaller areas.
Algorithm:
- Initialize
left = 0,right = n - 1. - Initialize
max_area = 0.