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.
**Notice** that you may not slant the container.
Examples
height = [1,8,6,2,5,4,8,3,7]49height = [1,1]1Constraints
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4
š” Hints
Hint 1
Start with the widest container (left=0, right=n-1) and try to find a taller one.
Hint 2
Always move the pointer pointing to the shorter line ā keeping the shorter line can never increase the area.
Algorithm Complexity
Official asymptotic Big-O runtime and auxiliary memory analysis
Two pointers from both ends. Calculate area at each position. Move the pointer with the shorter height ā keeping the shorter line can't produce a larger area since width is already decreasing.
Two pointers start at opposite ends and move toward each other, inspecting each line at most once.
Only requires two index pointers and a scalar variable to track maximum area in O(1) memory.
š Real-World Use Cases
Finding the optimal placement of two dividers in a warehouse to maximize storage volume between them.
Identifying the maximum potential profit window between two price points in a time series.
š Dry Run
Initialize left=0 (height 1), right=5 (height 7), maxArea=0