Container With Most Water in Java
This guide explains the intuition, optimized approach, and Java implementation for container with most water in java, with practical tips for interviews and production coding standards.
Problem
Given heights of vertical lines, find two lines forming a container with maximum water.
Brute Force vs Optimal
- Brute force: check all pairs ->
O(n^2) - Optimal: two pointers from both ends ->
O(n)
Key Insight
Area = min(height[left], height[right]) * (right - left).
Move the pointer with smaller height, because moving the taller one cannot increase the limiting height.
Java Solution
class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int best = 0;
while (left < right) {
int h = Math.min(height[left], height[right]);
int w = right - left;
best = Math.max(best, h * w);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}
}
Complexity
- Time:
O(n) - Space:
O(1)
Key Takeaways
- Start from the brute-force idea, then derive the optimized invariant.
- Use clean pointer/index boundaries to avoid off-by-one bugs.
- Validate against edge cases (empty input, single element, duplicates, extreme values).