Back to DSA track
Two Pointers

Container With Most Water

Pick two lines that trap the maximum water, where area depends on the shorter height and the distance between them.

This is a strong example of why the movement rule matters more than memorizing the pattern name.
It teaches a common interview proof: why a specific pointer move is safe.

Problem intuition

Brute force tries every pair and computes the area directly.

The optimal move is to start from the widest container and shrink only the shorter wall, because moving the taller wall cannot increase the height bottleneck.

Java solution ladder

The solutions below are ordered from least optimal to most optimal, so you can see the improvement path instead of only the final answer.

Solution 1

Brute force all pairs

O(n^2)O(1)

Compute the area for every pair of lines and keep the largest value. Easy to reason about, but quadratic.

class Solution {
    public int maxArea(int[] height) {
        int best = 0;

        for (int i = 0; i < height.length; i++) {
            for (int j = i + 1; j < height.length; j++) {
                int width = j - i;
                int area = Math.min(height[i], height[j]) * width;
                best = Math.max(best, area);
            }
        }

        return best;
    }
}

Solution 2

Two pointers from the widest span

O(n)O(1)

Begin at both ends and always move the shorter wall inward. That is the only move with a chance of improving the bottleneck height.

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;
    }
}