Container With Most Water

mediumTwo Pointers44 stepsJava · Python · C++

Pick two lines that hold the most water: area = min(height) × width. Start with the widest pair and always move the shorter line inward, since keeping it can never produce a bigger area.

▶ Watch the animated trace

Traced input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7] → 49. Original problem: neetcode.io/problems/max-water-container

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

Each step discards one line.

Key idea

Common mistakes

Solution

Java
int maxArea(int[] height) {
    int l = 0, r = height.length - 1, best = 0;
    while (l < r) {
        int area = Math.min(height[l], height[r]) * (r - l);
        best = Math.max(best, area);
        if (height[l] < height[r]) l++;
        else r--;
    }
    return best;
}
Python
def maxArea(height: List[int]) -> int:
    l, r, best = 0, len(height) - 1, 0
    while l < r:
        area = min(height[l], height[r]) * (r - l)
        best = max(best, area)
        if height[l] < height[r]: l += 1
        else: r -= 1
    return best
C++
int maxArea(vector<int>& height) {
    int l = 0, r = (int)height.size() - 1, best = 0;
    while (l < r) {
        int area = min(height[l], height[r]) * (r - l);
        best = max(best, area);
        if (height[l] < height[r]) l++;
        else r--;
    }
    return best;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Two lines
One pair, width 1.
height = [1, 1]1
Equal heights
The widest pair wins.
height = [4, 4, 4, 4]12
Increasing heights
Best is 2 × 3 or 3 × 2.
height = [1, 2, 3, 4, 5]6
Zero heights
Every pair includes a line of height 0, so nothing is held.
height = [0, 2, 0]0
← 3SumTrapping Rain Water →