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

Examples:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: Lines at index 1 (height 8) and index 8 (height 7) form a container of area 7 * 7 = 49.

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

Problem Breakdown:

  1. Use two pointers starting at the leftmost and rightmost lines. Calculate the area formed between them.
    • left = 0
      right = len(height) - 1
      maxArea = 0
  2. While the pointers have not crossed, calculate the area: width * min(height[left], height[right]).
    • while left < right:
          area = (right - left) * min(height[left], height[right])
          maxArea = max(maxArea, area)
  3. Move the pointer pointing to the shorter line inward. Moving the taller line would only decrease the area (width shrinks and height cannot increase).
    •     if height[left] < height[right]:
              left += 1
          else:
              right -= 1
  4. Return the maximum area found.
    • return maxArea

Summary:

Two pointers from both ends. Calculate area at each step. Always move the shorter side inward because the area is limited by the shorter line, and moving it might find a taller line. Moving the taller side can only decrease area.

Time and Space Complexity:

Time Complexity: O(n) - each pointer moves at most n times total.

Space Complexity: O(1) - only constant extra space.

Python Solution:

def maxArea(height):
    left, right = 0, len(height) - 1
    maxArea = 0
    while left < right:
        area = (right - left) * min(height[left], height[right])
        maxArea = max(maxArea, area)
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return maxArea

JavaScript Solution:

var maxArea = function(height) {
    let left = 0, right = height.length - 1, maxArea = 0;
    while (left < right) {
        const area = (right - left) * Math.min(height[left], height[right]);
        maxArea = Math.max(maxArea, area);
        if (height[left] < height[right]) left++;
        else right--;
    }
    return maxArea;
};

Java Solution:

class Solution {
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1, maxArea = 0;
        while (left < right) {
            int area = (right - left) * Math.min(height[left], height[right]);
            maxArea = Math.max(maxArea, area);
            if (height[left] < height[right]) left++;
            else right--;
        }
        return maxArea;
    }
}