Container With Most Water - Problem

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: You may not slant the container.

Input & Output

Example 1 — Basic Case
$ Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
💡 Note: The vertical lines are at positions with heights [1,8,6,2,5,4,8,3,7]. The maximum area is between lines at indices 1 and 8: area = (8-1) × min(8,7) = 7 × 7 = 49
Example 2 — Minimum Case
$ Input: height = [1,1]
Output: 1
💡 Note: Only two lines available: area = (1-0) × min(1,1) = 1 × 1 = 1
Example 3 — Equal Heights
$ Input: height = [4,3,2,1,4]
Output: 16
💡 Note: Maximum area is between first and last lines: area = (4-0) × min(4,4) = 4 × 4 = 16

Constraints

  • n == height.length
  • 2 ≤ n ≤ 105
  • 0 ≤ height[i] ≤ 104

Visualization

Tap to expand
Container With Most Water Problem186254837Water ContainerArea = 7 × 7 = 49Width = 7Goal: Find two lines thatform maximum water areaArea = width × min(height1, height2)Maximum Area = 49
Understanding the Visualization
1
Input
Array of heights representing vertical lines
2
Process
Find two lines that form the largest water container
3
Output
Maximum water area possible
Key Takeaway
🎯 Key Insight: Water level is always limited by the shorter line, so use two pointers and always move from the shorter side
Asked in
Amazon 42 Google 38 Microsoft 35 Apple 28 Facebook 24
892.0K Views
High Frequency
~15 min Avg. Time
15.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen