📘
Container With Most Water
MediumTwo Pointers
Given n non-negative integers representing heights of vertical lines, find two lines that together with the x-axis form a container holding the most water.
Example:
Input:
1,8,6,2,5,4,8,3,7
Output:
49
Reasoning:
- The input array represents the heights of vertical lines, and we need to find the two lines that form a container holding the most water.
- We start by considering the area between the first and last lines, which is 8⋅8=64 (since the width is 8 and the height is the minimum of the two lines, which is 8), but the actual area is limited by the shorter line, so we consider other pairs.
- We then move the pointers towards the center, calculating the area for each pair of lines, such as 7⋅7=49 (since the width is 7 and the height is the minimum of the two lines, which is 7), and keep track of the maximum area found.
- The maximum area found is 49, which occurs when the two lines of height 7 and 8 (with 7 being the minimum) are used to form the container, giving a width of 7 and resulting in the maximum area of 7⋅7=49.
Constraints:
- 2 <= len(height) <= 10^5
- 0 <= height[i] <= 10^4
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.