codejump
MediumPythonJavaScriptTypeScript

Two Pointers — Container With Most Water

AlgorithmsTwo PointersArraysGreedy

heights[i] is the height of a vertical line at position i. Pick two lines:
together with the x-axis they form a container holding
min(heights[i], heights[j]) * (j - i) units of water.

Return the largest amount of water any pair of lines can hold.

Trying every pair is O(n²). Start with the widest container (both ends) and
move one pointer inward at each step: only moving the shorter line can
ever find a taller wall, so the other move is never worth trying. That makes it
O(n).

Examples

solve([1, 8, 6, 2, 5, 4, 8, 3, 7])  → 49   // lines at 1 and 8: min(8, 7) * 7
solve([1, 1])                       → 1
solve([4, 3, 2, 1, 4])              → 16

Constraints

  • 2 <= heights.length <= 100000
  • 0 <= heights[i] <= 10000

Sample tests

Test #1The classic example
Input: [[1,8,6,2,5,4,8,3,7]]
Output: 49
Test #2Two lines only
Input: [[1,1]]
Output: 1
Test #3The best pair is the widest one
Input: [[4,3,2,1,4]]
Output: 16