Container With Most Water

Given wall heights, pick two walls that, with the ground, hold the most water. Return that amount of water.

A way to picture it

Two walls hold water, and the shorter wall decides how high the water goes. Start with the widest pair. Moving the taller wall inward can only make the container narrower without raising the water, so always move the shorter one.

How to approach it

Start at both ends. Water = min(height) × width. Move the pointer at the shorter wall, because it's the bottleneck.

Example

Input: {"height":[1,8,6,2,5,4,8,3,7]}. Output: 49.

Complexity: O(n) time and O(1) space. Each step moves one pointer inward.

This page includes an animated walkthrough, Java and Python solutions, and a question to check your understanding.