Each number is the height of a wall. Pick two walls, and the water they hold is the gap between them times the shorter wall, because water spills over the lower side.
There are 36 pairs here. Checking them all is ; this post gets there in 8 steps.
Start wide, then drop the shorter wall
Start with the widest container you can: the two end walls.
It holds 8, capped by wall 0 at height 1. Now ask: could wall 0 be part of a better container? Any other partner sits closer to it, so the width shrinks, and the height can never go above 1 because wall 0 is still the shorter side. Every container that uses wall 0 is worse than this one. Wall 0 is finished, so move the left pointer in.
The same argument works at every step: the shorter wall has already had its best container, so drop it. Moving the taller wall instead can only shrink the width while the cap stays put, which is the one bug this problem has.
| L (height) | R (height) | Area | Move |
|---|---|---|---|
| 0 (1) | 8 (7) | 8 × 1 = 8 | left is shorter |
| 1 (8) | 8 (7) | 7 × 7 = 49 | right is shorter, best |
| 1 (8) | 7 (3) | 6 × 3 = 18 | right |
| 1 (8) | 6 (8) | 5 × 8 = 40 | equal, either is safe |
| 1 (8) | 5 (4) | 4 × 4 = 16 | right |
| 1 (8) | 4 (5) | 3 × 5 = 15 | right |
| 1 (8) | 3 (2) | 2 × 2 = 4 | right |
| 1 (8) | 2 (6) | 1 × 6 = 6 | pointers meet |
When the walls are equal, both are capped at the same height and anything narrower can't beat it, so moving either one is safe.
Record, then drop the shorter wall
Record the area first, then move: moving first skips a container.
time, since each wall is dropped once, and space.
This is the same move as Two Sum II: start at the ends, and let one comparison prove a side can never help. Don't confuse it with Trapping Rain Water, which sums the water above every bar and needs the running maximum from each side, not just the best pair.