Container With Most Water
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, heighti). Find two lines that together with the x-axis form a container, such that the container contains the most water . Return the maximum amount of water a container can store. Notice that you may not slant the container. Start pointers at both ends and always move the pointer at the shorter line inward — moving the taller line can only shrink the width without any chance of gaining height.
Constraints
- n == height.length
- 2 ≤ n ≤ 105
- 0 ≤ heighti ≤ 104
Example
height = [1, 8, 6, 2, 5, 4, 8, 3, 7]49Explanation Lines at index 1 (height 8) and index 8 (height 7) form the container: width 7 x height min(8, 7) = 7 gives area 49, the maximum possible.
Converge two pointers, always moving the shorter side
left=1 (idx 0), right=7 (idx 8): width 8 x min(1, 7) = 8. best = 8.
What happens in this step
left = 0 (height 1), right = 8 (height 7) width = 8 - 0 = 8, area = 8 x min(1, 7) = 8 height[left]=1 is the shorter side, so left moves inward from index 0 to index 1. Best area so far: 8.
Steps to visualize
- Point left at the first line and right at the last line.
- Compute the area: width between the pointers times the shorter of the two heights.
- Update the best area seen so far.
- Move whichever pointer is at the shorter line one step inward.
- Stop when the pointers meet.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
left=1 (idx 0), right=7 (idx 8): width 8 x min(1, 7) = 8. best = 8.
What happens in this step
left = 0 (height 1), right = 8 (height 7) width = 8 - 0 = 8, area = 8 x min(1, 7) = 8 height[left]=1 is the shorter side, so left moves inward from index 0 to index 1. Best area so far: 8.
Solution
function maxArea(height) {
let left = 0;
let right = height.length - 1;
let best = 0;
while (left < right) {
const width = right - left;
const area = width * Math.min(height[left], height[right]);
best = Math.max(best, area);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return best;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
height = [1, 8, 6, 2, 5, 4, 8, 3, 7] | 49 | example from the docstring |
height = [1, 1] | 1 | smallest valid input: only two lines |
height = [4, 4, 4, 4] | 12 | every line the same height, so width alone decides the winner |
height = [1, 2, 3, 4, 5, 6] | 9 | strictly increasing heights favor a middle pair, not the ends |
height = [0, 3, 0, 5, 0] | 6 | a zero-height line at the boundary holds no water |