Skip to main content

Container with Most Water

MediumPremium

Given an array of non-negative integers where each value represents the height of a vertical line at that index on the x-axis, determine the maximum amount of water that can be trapped between any two lines.

A container is formed by selecting any two lines and the x-axis. The amount of water the container can hold is determined by the shorter of the two lines (as water cannot overflow the shorter one) and the distance between the two lines (which determines the width).

Your goal is to identify the pair of lines that together form a container with the maximum possible area (height × width).

Container with Most Water

Example 1

Input: [2, 9, 6, 2, 5, 3, 5, 10, 1] Output: 54

The maximum container is formed between the lines at index 1 (height = 9) and index 7 (height = 10). The shorter line determines the height (9), and the width between them is 6. So, the area is 9 × 6 = 54.

Example 2

Input: [1, 1] Output: 1

There is only one possible container between the two lines, both of height 1. The width is 1, so the area is 1 × 1 = 1.