You're given a row of vertical walls of varying heights, described by an array of non-negative integers. Picture each number as the height of a wall standing on a flat line, one unit apart. Pick any two walls and they form the sides of a container; the water it holds is bounded by the shorter of the two walls and stretches across the horizontal gap between them. Your job is to find the two walls that trap the most water and return that area.
This is the classic "Container With Most Water" problem. The water area between walls at indices i and j is min(height[i], height[j]) * (j - i) — the shorter wall caps the depth, and the index distance is the width.
// heights: number[] — non-negative wall heights, one unit apart on the x-axis.
// returns: number — the maximum water area between any two walls. 0 if fewer than two walls.
function maximumWaterBetweenWalls(heights);
maximumWaterBetweenWalls([1, 8, 6, 2, 5, 4, 8, 3, 7]); // → 49
// Walls at index 1 (height 8) and index 8 (height 7):
// min(8, 7) * (8 - 1) = 7 * 7 = 49.
maximumWaterBetweenWalls([1, 1]); // → 1
// min(1, 1) * (1 - 0) = 1 * 1 = 1.
maximumWaterBetweenWalls([4, 3, 2, 1, 4]); // → 16
// The two height-4 walls at the ends: min(4, 4) * (4 - 0) = 16.
// A tall, wide container beats every narrower one in between.
i < j, the trapped water is min(height[i], height[j]) * (j - i). The shorter wall sets the depth; the gap between indices sets the width.i and j is simply j - i.0.0 can be one side of a container, but the min makes that container hold 0 water.