Container With Most Water
Why it belongs on this sheet
It is a classic two-pointer problem where brute force is easy to think of, but the greedy elimination is the real interview value.
Pattern
Move the limiting side
Approach
Start with the widest container. The height is limited by the shorter wall, so moving the taller wall cannot help if the shorter wall stays the bottleneck. Move the shorter side inward.
Java solution
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int best = 0;
while (left < right) {
int width = right - left;
int area = Math.min(height[left], height[right]) * width;
best = Math.max(best, area);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}
}
Complexity
- Time:
O(n) - Space:
O(1)
Interview note
What matters here is the proof idea for why moving the shorter side is safe.