The 30 second answer
I start with one pointer at each end of the height array. The area is the smaller of the two heights times the distance between them. I then move the pointer on the shorter side, because shrinking the width can only help if the next line is taller. I keep the best area. That is one pass and constant extra space.
Problem You are given the heights of vertical lines drawn at positions 0 to n−1. Choose two lines so that together with the x-axis they form a container holding as much water as possible, and return that maximum area. Original: LeetCode 11: Container With Most Water.
Understanding the prompt The water cannot pile higher than the shorter of the two chosen lines, and it cannot leak between them: the area is min(height[lo], height[hi]) * (hi - lo). You need the maximum over all pairs, not a pair that uses the tallest line.
Pattern recognition Opposite-ends two pointers on a width that only shrinks. You move the side that is the current bottleneck.
Brute force Evaluate the area of every pair: O(n²).
Optimal Start at both ends, so the width is as large as it can be. Record the area, then advance the shorter pointer. The width will get smaller, so a better area is possible only with a taller line on that side. If the two heights are equal, either pointer can move.
Alternatives There is no useful hash-map version. A monotonic stack does not help here; save that for Trapping Rain Water or the histogram rectangle.
Java solution
public class ContainerWithMostWater {
static int maxArea(int[] height) {
int lo = 0, hi = height.length - 1, best = 0;
while (lo < hi) {
int h = Math.min(height[lo], height[hi]);
best = Math.max(best, h * (hi - lo));
if (height[lo] < height[hi]) lo++;
else hi--;
}
return best;
}
public static void main(String[] args) {
System.out.println(maxArea(new int[] {1, 8, 6, 2, 5, 4, 8, 3, 7})); // 49
System.out.println(maxArea(new int[] {1, 1})); // 1
System.out.println(maxArea(new int[] {1, 2, 1})); // 2
}
}Complexity O(n) time, O(1) extra space.
Edge cases
- Two lines only, as in [1,1], whose area is 1.
- A tall line in the middle that is never chosen, because a shorter pair farther apart wins.
Follow-ups
- Trapping Rain Water, where every index can hold water, not just the two sides of one container.
- What if the heights arrive as a stream? You would need a different structure; say so.
Tests [1,8,6,2,5,4,8,3,7] returns 49. [1,1] returns 1. [1,2,1] returns 2.
How to say it in the interview "I start at both ends. The area is the min height times the width. Then I move the shorter side, because the width is shrinking and only a taller line can beat the area I already have. One pass, constant space."
Sources (2)
- LeetCode 11: Container With Most Waterleetcode.com
- Java SE 17 API: Math.mindocs.oracle.com