Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Container With Most Water

Problem Statement

Given an array of heights representing vertical lines, find two lines that, together with the x-axis, form a container that holds the most water. This is a medium-level problem solved using two pointers.

Example

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

Output: 49 (lines at indices 1 and 8 with height 7 and width 7 form area 49)

Code

Java
Python
JavaScript
public class Solution {
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1;
        int maxWater = 0;
        
        while (left < right) {
            int width = right - left;
            int minHeight = Math.min(height[left], height[right]);
            maxWater = Math.max(maxWater, width * minHeight);
            
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return maxWater;
    }
}
            
def max_area(height):
    left, right = 0, len(height) - 1
    max_water = 0
    
    while left < right:
        width = right - left
        min_height = min(height[left], height[right])
        max_water = max(max_water, width * min_height)
        
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return max_water

# Example usage
print(max_area([1, 8, 6, 2, 5, 4, 8, 3, 7]))  # 49
            
function maxArea(height) {
    let left = 0, right = height.length - 1;
    let maxWater = 0;
    
    while (left < right) {
        let width = right - left;
        let minHeight = Math.min(height[left], height[right]);
        maxWater = Math.max(maxWater, width * minHeight);
        
        if (height[left] < height[right]) {
            left++;
        } else {
            right--;
        }
    }
    return maxWater;
}

// Example usage
console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])); // 49
            

Explanation

  • Use two pointers: left at start, right at end.
  • Calculate area as width (distance between pointers) times the minimum height.
  • Update max area if current area is larger.
  • Move the pointer with the shorter height inward to potentially increase area.

Note

Time complexity is O(n) with a single pass. Space complexity is O(1).