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.
Examples
Example 1
`height = [1, 8, 6, 2, 5, 4, 8, 3, 7]``49`Example 2
`height = [1, 1]``1`Example 3
`height = [1, 2, 1]``2`Constraints
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4
Hints
Hint 1
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.Hint 2
Opposite-ends two pointers on a width that only shrinks. You move the side that is the current bottleneck.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
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.
Alternative. There is no useful hash-map version. A monotonic stack does not help here; save that for Trapping Rain Water or the histogram rectangle.
Complexity
- Time
- O(n)
O(n) time, O(1) extra space.
- Space
- O(1)
Code
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
}
}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.
Interview script
"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."
Source: LeetCode 11: Container With Most Water Source: Java SE 17 API: Math.min)
Sources (2)
- LeetCode 11: Container With Most Waterleetcode.com
- Java SE 17 API: Math.mindocs.oracle.com