The Problem

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

Find two lines that together with the x-axis forms 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.

The area between two lines at positions left and right is: area = (right - left) * min(height[left], height[right]).

Interactive Visualization

Speed:
Height Bars
Press Step or Play to begin.
โ€”
Current Area
0
Max Area
โ€”
Width
โ€”
Min Height
Code
fun maxArea(height: IntArray): Int {    var left = 0; var right = height.size - 1    var maxArea = 0    while (left < right) {        val w = right - left        val h = minOf(height[left], height[right])        val area = w * h        maxArea = maxOf(maxArea, area)        if (height[left] < height[right])            left++        else            right--    }    return maxArea}
Current Step
Press Step or Play to begin.

How It Works

Key Insight

The area between two lines is determined by the shorter line and the distance between them: area = width * min(height[left], height[right]). Starting with the widest container (pointers at both ends), we can only potentially increase the area by moving the shorter side inward โ€” moving the taller side would only decrease the width while the height is still limited by the shorter side.

The Algorithm

  • Initialize: Place left at the start (index 0) and right at the end (index n-1)
  • Each iteration: Calculate the area formed by the two lines at left and right
  • Update max: If the current area exceeds max_area, update it
  • Move the shorter side: If height[left] < height[right], move left right (increment); otherwise move right left (decrement)
  • When left meets right: All possible optimal containers have been considered; return max_area

Why Move the Shorter Side?

If we move the taller side inward, the width decreases by 1 and the height can only stay the same or decrease (since it's bounded by the shorter side). So the area would definitely not increase. By moving the shorter side, we have a chance of finding a taller line that could increase the area despite the reduced width.

Complexity

Time O(n)
Space O(1)

Each pointer moves at most n - 1 steps total, and each step does constant work. We use only a fixed number of variables.