Container With Most Water - Problem
Imagine you're designing a water collection system using vertical walls! You're given an array of n positive integers representing the height of vertical lines positioned at equal distances along the x-axis.
Each line i extends from point (i, 0) to (i, height[i]). Your goal is to find two lines that, together with the x-axis, form a container that can hold the maximum amount of water.
Key Rules:
- The container cannot be tilted (must be upright)
- Water level is limited by the shorter of the two walls
- The wider the container, the more water it can potentially hold
- Return the maximum area of water that can be contained
Formula: Area = min(height[i], height[j]) ร (j - i)
Input & Output
example_1.py โ Standard Case
$
Input:
[1,8,6,2,5,4,8,3,7]
โบ
Output:
49
๐ก Note:
The maximum area is between lines at indices 1 and 8 (heights 8 and 7). Area = min(8,7) ร (8-1) = 7 ร 7 = 49.
example_2.py โ Minimal Case
$
Input:
[1,1]
โบ
Output:
1
๐ก Note:
Only two lines available, both with height 1. Area = min(1,1) ร (1-0) = 1 ร 1 = 1.
example_3.py โ Ascending Heights
$
Input:
[2,3,4,5,18,17,6]
โบ
Output:
17
๐ก Note:
Maximum area is between indices 4 and 5 (heights 18 and 17). Area = min(18,17) ร (5-4) = 17 ร 1 = 17.
Visualization
Tap to expand
Understanding the Visualization
1
Set Up Walls
Visualize vertical lines as walls that can contain water
2
Start Wide
Begin with leftmost and rightmost walls (maximum width)
3
Move Strategically
Always move the pointer at the shorter wall inward
4
Find Maximum
Continue until pointers meet, tracking maximum area
Key Takeaway
๐ฏ Key Insight: Always move the pointer at the shorter wall because moving the taller wall would only decrease the total area while reducing width.
Time & Space Complexity
Time Complexity
O(nยฒ)
We check all possible pairs of lines, which gives us nร(n-1)/2 combinations
โ Quadratic Growth
Space Complexity
O(1)
Only using a few variables to track maximum area and current calculations
โ Linear Space
Constraints
- n == height.length
- 2 โค n โค 105
- 0 โค height[i] โค 104
- At least two lines are always provided
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code