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 INPUT 0 1 2 3 4 5 6 7 8 height array: [1,8,6,2,5,4,8,3,7] n = 9 elements ALGORITHM STEPS 1 Initialize Pointers left=0, right=n-1 2 Calculate Area width * min(h[L], h[R]) 3 Update Max Area maxArea = max(maxArea, area) 4 Move Shorter Pointer if h[L] < h[R]: L++ else: R-- Best Container Found: L=1 R=8 w=7 h=7 49 FINAL RESULT width = 7 height = 7 Maximum Water: 49 [OK] Area = 7 x 7 = 49 Indices: 1 and 8 Key Insight: The greedy two-pointer approach works because moving the shorter line inward is the only way to potentially find a larger container. Moving the taller line would only decrease width while the height is still limited by the shorter line. Time: O(n), Space: O(1). TutorialsPoint - Container With Most Water | Greedy Two-Pointer Approach
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