[/dsa/leetcode]

11 - Container With Most Water

Wednesday, 16 September 2026

<medium> [problem]

Converging pointers that always discard the shorter wall, because it is the one nothing further inward can rescue.

{array}{two pointers}{greedy}

Problem

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store.

Notice that you may not slant the container.

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

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

Constraints:

  • n == height.length
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4

Approach

Water held between l and r is bounded by the shorter of the two walls — the excess of the taller one just spills over it:

area = min(height[l], height[r]) * (r - l)

We start with the widest possible container, l = 0 and r = n - 1, and move inward. Width only ever shrinks from here, so any later container has to make up for it with more height. At each step the smaller one of the container walls is discarded as that would maximize the container area.

class Solution {
public:
    int maxArea(vector<int>& height) {
        int l = 0, r = height.size() - 1;
        int maxi = 0;
        while (l < r) {
            int mini = min(height[l], height[r]);
            int area = mini * (r - l);
            maxi = max(maxi, area);
            if (height[l] < height[r]) {
                l++;
            } else {
                r--;
            }
        }
        return maxi;
    }
};
height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
l=0 r=8  min(1,7)=1  w=8  area=8     1 < 7,  l++
l=1 r=8  min(8,7)=7  w=7  area=49    8 >= 7, r--
l=1 r=7  min(8,3)=3  w=6  area=18    r--
l=1 r=6  min(8,8)=8  w=5  area=40    equal,  r--
l=1 r=5  min(8,4)=4  w=4  area=16    r--
l=1 r=4  min(8,5)=5  w=3  area=15    r--
l=1 r=3  min(8,2)=2  w=2  area=4     r--
l=1 r=2  min(8,6)=6  w=1  area=6     r--
l=1 r=1  stop                        max = 49
  • time: O(n) — every iteration discards one wall, so at most n - 1 iterations
  • space: O(1) — two indices
quantinium © 2026