Move the shorter wall inward
Updated
With two walls at L and R the water they hold is (R − L) × min(h[L], h[R]). Moving the taller wall can never help, because the shorter one still caps the height. So move the shorter wall inward and keep the best area seen.
What to focus on
Start at the two ends. Each step shrinks the width by one, so only a taller limiting wall can beat the current best. That is why the shorter side is the one to give up.
Worked examples
classic
h = [1, 8, 6, 2, 5, 4, 8, 3, 7]- L=1 and R=8 give 7 × 7
Result: 49
two walls
a = [1, 8, 6, 2, 5, 4, 8, 3, 7], h = [1, 1]- width 1, height 1
Result: 1
equal ends
h = [4, 3, 2, 1, 4]- L=0 and R=4 give 4 × 4
Result: 16
Try it
Write maxArea(h). h is an array of non-negative integers, the wall heights. Return the largest (R - L) * min(h[L], h[R]) over all pairs, using two pointers that always move the shorter wall inward. On [1, 8, 6, 2, 5, 4, 8, 3, 7] return 49. On [1, 1] return 1. On [4, 3, 2, 1, 4] return 16.
h has length ≥ 2. Heights are non-negative integers.