← Back to Leo Academy Masterclass

Problem #11: Container With Most Water

Medium Two Pointers

Intuition & Strategy Breakdown

Use two pointers starting at both ends of the array. Calculate area using the shorter height, then move the pointer pointing to the shorter line inward to maximize potential container area.

Python Solution

class Solution:
    def maxArea(self, height: list[int]) -> int:
        l, r = 0, len(height) - 1
        max_area = 0
        while l < r:
            area = min(height[l], height[r]) * (r - l)
            max_area = max(max_area, area)
            if height[l] < height[r]:
                l += 1
            else:
                r -= 1
        return max_area

Java Solution

class Solution {
    public int maxArea(int[] height) {
        int l = 0, r = height.length - 1;
        int maxArea = 0;
        while (l < r) {
            int area = Math.min(height[l], height[r]) * (r - l);
            maxArea = Math.max(maxArea, area);
            if (height[l] < height[r]) {
                l++;
            } else {
                r--;
            }
        }
        return maxArea;
    }
}
Watch Interactive Video on Leo Academy Main App