Maximum Water Trapped Between WallsLoading saved progress…

Maximum Water Trapped Between Walls

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.

Signature

// 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);

Examples

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.

Notes

  • Area formula. For walls at indices 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.
  • This is not "Trapping Rain Water." That related problem sums water held across every dip in the skyline. Here you pick exactly one container formed by two walls — no partitions in between, no summing.
  • Width is index distance, not value distance. Walls sit one unit apart, so the width between index i and j is simply j - i.
  • Fewer than two walls hold no water. An empty array or a single wall returns 0.
  • Heights can be zero. A wall of height 0 can be one side of a container, but the min makes that container hold 0 water.
Loading editor…