Container With Most Water
You are given an integer array heightnnith(i, 0)(i, height[i])
Example 1
Output: 49
Explanation: Lines at indices 1 and 8 (values 8 and 7). Width = 7, height = min(8,7) = 7. Area = 49.
Example 2
Output: 1
Constraints:
n == height.length2 <= n <= 1050 <= height[i] <= 104
Approach 1: Brute Force O(n²)
Try every pair of lines and compute the contained area.
public int maxArea(int[] height) {
int max = 0;
for (int i = 0; i < height.length - 1; i++) {
for (int j = i + 1; j < height.length; j++) {
int area = (j - i) * Math.min(height[i], height[j]);
max = Math.max(max, area);
}
}
return max;
}
Approach 2: Two Pointers O(n)
Key insight: Area = width × min(height[left], height[right]). Width decreases as we move pointers inward. To maximise area we must try to increase height, so we always move the pointer pointing at the shorter line.
Why? Moving the taller line inward can only decrease or maintain width while the height is still limited by the shorter line. So moving the shorter line gives a chance to find a taller one.
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int maxWater = 0;
while (left < right) {
int width = right - left;
int minH = Math.min(height[left], height[right]);
maxWater = Math.max(maxWater, width * minH);
// Move the shorter line inward
if (height[left] <= height[right]) {
left++;
} else {
right--;
}
}
return maxWater;
}
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Brute Force | O(n²) | O(1) |
| Two Pointers | O(n) | O(1) |