#11MediumTwo Pointers

Container With Most Water

Shrink from both ends, always moving the shorter height inward.

AmazonMicrosoftGoldman SachsUberLinkedIn

Problem Statement

You are given an integer array height of length n. There are n vertical lines where the endpoints of line i are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container that holds the most water.

Examples

Example 1

Input:height = [1,8,6,2,5,4,8,3,7]
Output:49

Explanation: Lines at index 1(h=8) and 8(h=7): width=7, min(8,7)=7, area=49.

Example 2

Input:height = [1,1]
Output:1

Constraints

  • n == height.length
  • 2 ≤ n ≤ 10⁵
  • 0 ≤ height[i] ≤ 10⁴

Solutions

1
Brute Force
TimeO(n²)SpaceO(1)

Try every pair of lines and compute water = (j - i) * min(height[i], height[j]). O(n²).

Visual Animation
def maxArea(height: list[int]) -> int:
    max_water = 0
    n = len(height)
    for i in range(n):
        for j in range(i+1, n):
            water = (j - i) * min(height[i], height[j])
            max_water = max(max_water, water)
    return max_water

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Two Pointers to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems