Logo for ammarahmed.ca
Medium
May 27, 2025
#two-pointer
#math

11. Container With Most Water

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.

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. 4

Example 2:

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

Constraints:

  • n == height.length
    • 2 <= n <= 105
      • 0 <= height[i] <= 104

        Approach

        We can use two pointers to solve this problem. Obviously, we want to track the maximum area that we see but without checking every possible combination. The optimal way to do this is by having two pointers on each side and always moving the pointers toward the larger bar. This works because we want to maximize width as well as height and consistently moving towards the larger bar while starting at the maximum width will ensure this.

        Complexity

        Time: O(n)

        We iterate through the array once

        Space: O(1)

        No extra space is created

        Solution

        1func maxArea(height []int) int { 2 l := 0 3 r := len(height) - 1 4 maxArea := 0 5 for l < r { 6 w := r - l 7 h := min(height[l], height[r]) 8 a := w * h 9 maxArea = max(maxArea, a) 10 if height[l] == height[r] { 11 l++ 12 r-- 13 } else if height[l] < height[r] { 14 l++ 15 } else { 16 r-- 17 } 18 } 19 return maxArea 20}