Skip to problem
←

Container With Most Water

Medium 0 attempts

You're given an integer array height with n elements. Picture n vertical lines, where the ith line runs from (i, 0) up to (i, height[i]). Choose two of these lines so that, together with the x-axis between them, they form a container holding as much water as possible, and return that maximum area.

The container cannot be tilted. Lines between the chosen sides do not reduce the available area.

Function contract

Implement maxArea(height), where height[i] is the height of the vertical line at horizontal coordinate i.

Output: The largest area (j - i) × min(height[i], height[j]) for distinct indices i < j.

Example 1

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

Example 2

Input
height = [1,1]
Output
1
Visual Aid
Choose the sides at indices 1 and 8
012345678Width 7 × height 7 = 49

The shorter side is height 7. Intermediate lines do not subtract from the highlighted water area.

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

Use two pointers starting at the edges. Compute the area as the distance between pointers times the shorter line's height. Move the pointer pointing to the shorter line inward, since moving the taller one can never increase the area.

javascript
function maxArea(height) {
  let left = 0, right = height.length - 1;
  let max = 0;

  while (left < right) {
    const area = (right - left) * Math.min(height[left], height[right]);
    max = Math.max(max, area);
    if (height[left] < height[right]) left++;
    else right--;
  }

  return max;
}

Time: O(n) Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript