Each number is the height of a vertical line. Pick two lines that, together with the x axis, hold the most water. The water is the shorter line times the distance between them.
DSA Animator › DSA Revision › Arrays › Container With Most Water
Remember: start widest, and always move the shorter line. The shorter line limits the water. The video solves Container With Most Water (LeetCode 11, Medium) with the Two Pointers pattern from the Arrays topic, and you can replay every step in the interactive Container With Most Water animation.
Each number is the height of a vertical line. Pick two lines that, together with the x axis, hold the most water. The water is the shorter line times the distance between them.
For 1, 8, 6, 2, 5, 4, 8, 3, 7, the best pair is the lines at index 1 and index 8. The shorter is 7, the width is 7, so the area is 49.
Checking every pair is O of n squared. And picking the two tallest lines fails, because the width matters too.
Start with the widest container, one pointer at each end. The water level is set by the shorter line, so moving the taller line inward can never help. So always move the shorter line inward, and keep the best area.
The ends are heights 1 and 7, width 8, so the area is 8. Height 1 is shorter, so the left pointer moves to height 8. Now 8 and 7, width 7, give 49, the new best. 7 is now shorter, so the right pointer moves left. The next areas are 18, then 40, then smaller ones, none better than 49. When the pointers meet, the answer is 49.
In code, start left at 0 and right at the end. Compute the area as the shorter height times the width, and keep the best. Move whichever pointer has the shorter line. Each step moves one pointer, so it's O of n time and O of 1 space.
Remember: start widest, and always move the shorter line. The shorter line limits the water.