#11

Container With Most Water

Medium Opposite ends, move the shorter

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Vertical lines stand at each index with given heights. Pick two lines that, with the x-axis, hold the most water. Return that amount.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: choose two walls that trap the most water.

Why this works: water = width × shorter wall. Start widest. Moving the taller wall can only lose width without raising the shorter wall, so always move the shorter one.

Example: [1, 8, 6, 2, 5, 4, 8, 3, 7]

l=0 (1), r=8 (7): area 8 → move ll=1 (8), r=8 (7): area 49 (best) → move r… no wider pair beats 49

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Moving the taller side, or moving both — you can skip the best pair.