Container With Most Water [Medium]

17 Aug 2026 2 min read
2
The Container With Most Water problem requires finding two lines that form a container capable of holding the maximum amount of water.

Problem

Given an integer array height, where each element represents the height of a vertical line, find two lines that together with the x-axis form a container capable of holding the maximum amount of water.

Return the maximum amount of water the container can store.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

height = [1,8,6,2,5,4,8,3,7] 

Output

49 

Solution

This solution uses the Two Pointer technique to find the maximum area efficiently.

One pointer starts at the beginning of the array, while the other starts at the end. The amount of water that can be stored is determined by the shorter of the two heights multiplied by the distance between them.

After calculating the current area, the pointer pointing to the shorter line is moved inward. Moving the taller line cannot increase the area because the shorter line still limits the container's height.

During the traversal, the maximum area encountered is continuously updated and returned as the answer.
public int maxArea(int[] height) {
    int left = 0;
    int right = height.length - 1;
    int maxArea = 0;

    while (left < right) {
        int width = right - left;
        int currentArea = Math.min(height[left], height[right]) * width;

        // Update the maximum area.
        maxArea = Math.max(maxArea, currentArea);

        // Move the shorter line.
        if (height[left] < height[right]) {
            left++;
        } else {
            right--;
        }
    }
    return maxArea;
}

Complexity

The algorithm traverses the array using two pointers. Since each pointer moves only toward the center, the overall time complexity is O(n).

Only a few variables are used to store the pointers and the maximum area, so the extra space complexity is O(1).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion