Logo for ammarahmed.ca
Medium
Dec 22, 2025
#two-pointers
#math

11. Container With Most Water

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.

Example 1:

1Input: height = [1,8,6,2,5,4,8,3,7] 2Output: 49 3Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:

1Input: height = [1,1] 2Output: 1
  • n == height.length
    • 2 <= n <= 105
      • 0 <= height[i] <= 104

        Constraints:

        Notes

        Intuition

        The area of water between two lines depends on both the width (distance between them) and the height (limited by the shorter line). Starting with maximum width and strategically reducing it toward taller lines gives us the best chance of finding the largest area.

        Implementation

        Place left and right pointers at opposite ends of the array. Calculate the current area using width * min(height[l], height[r]) and track the maximum. Move the pointer pointing to the shorter line inward—if height[l] > height[r], decrement r; otherwise, increment l. This ensures we always explore potentially larger areas.

        Edge-cases

        No special edge cases. The algorithm naturally handles arrays of any valid length.

        • Time: O(n) — each pointer moves at most n times
          • Space: O(1) — only tracking pointers and max area

            Complexity

            Solution

            1from typing import List 2 3class Solution: 4 def maxArea(self, height: List[int]) -> int: 5 l, r, maxArea = 0, len(height) - 1, 0 6 7 while l < r: 8 w = r - l 9 h = min(height[l], height[r]) 10 maxArea = max(maxArea, w * h) 11 if height[l] > height[r]: 12 r -= 1 13 else: 14 l += 1 15 16 17 return maxArea 18 19 20 21 22if __name__ == "__main__": 23 # Include one-off tests here or debugging logic that can be run by running this file 24 # e.g. print(solution.two_sum([1, 2, 3, 4], 3)) 25 solution = Solution() 26