Container With Most Water Medium 0 attempts
LeetCode ↗

Container With Most Water

Medium ArrayTwo Pointers LeetCode

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.

Sample Input
height = [1,8,6,2,5,4,8,3,7]
Sample Output
49
Constraints
  • 2 <= height.length <= 10^5
  • 0 <= height[i] <= 10^4
Test Cases
Case 1
Args: [[1,8,6,2,5,4,8,3,7]] Expected: 49

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.

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)

Saved in this browser only. Private to you.

JavaScript