sagelearnai

Container With Most Water

Difficulty: Medium · Pattern: Two Pointers · LeetCode #11

height[i] is the height of a vertical wall at position i. Choosing two walls i < j forms a container holding (j − i) × min(height[i], height[j]) units of water. Return the maximum water any pair can hold.

Examples

text
height = [2, 5, 4, 1, 6, 3]  →  15    (walls at 1 and 4: width 3 × height 5)
height = [3, 3]              →  3

Hints

  1. Start with the widest container: the first and last wall.
  2. The area is limited by the shorter wall. Would moving the taller wall ever help?

Approach

Start with l = 0, r = n − 1 and record the area. Then move the pointer at the shorter wall inward.

Why: for the shorter wall at l, every other container using it with some r' < r is narrower and still capped at height[l], so it can't beat the current area. That wall is done; discard it. Repeating this checks all candidates that could be optimal in O(n).

Complexity

Time: O(n). Space: O(1).

Python solution
def maxArea(height):
    l, r, best = 0, len(height) - 1, 0
    while l < r:
        best = max(best, (r - l) * min(height[l], height[r]))
        if height[l] < height[r]:
            l += 1
        else:
            r -= 1
    return best
JavaScript solution
function maxArea(height) {
  let l = 0, r = height.length - 1, best = 0;
  while (l < r) {
    best = Math.max(best, (r - l) * Math.min(height[l], height[r]));
    if (height[l] < height[r]) l++; else r--;
  }
  return best;
}