Intuition
Start with the widest container (left=0, right=n-1). Move the shorter side inward since it limits the height and we're reducing width.
Explanation
Approach
- Two pointers at both ends.
- Compute area = min(left_h, right_h) * width.
- Move the pointer with the shorter height inward.
- Track maximum area.
Complexity
- Time: O(n)
- Space: O(1)
Implementation
class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int maxWater = 0;
while (left < right) {
int w = right - left;
int h = Math.min(height[left], height[right]);
maxWater = Math.max(maxWater, w * h);
if (height[left] < height[right]) left++;
else right--;
}
return maxWater;
}
}