题目
给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
示例:
输入: [1,8,6,2,5,4,8,3,7]
输出: 49
解
由于最大高度由两侧距离和两端较小的距离决定,所以我们使用两个指针跟踪两侧的值,在较小的一端向中间靠拢。
class Solution:
def maxArea(self, height: List[int]) -> int:
lIndex=0
rIndex=len(height)-1
maxH=min(height[lIndex],height[rIndex])*(rIndex-lIndex)
while(rIndex > lIndex):
if height[lIndex] < height[rIndex]:
lIndex += 1
maxH = max(maxH,(rIndex-lIndex)*min(height[lIndex],height[rIndex]))
else:
rIndex -= 1
maxH = max(maxH,(rIndex-lIndex)*min(height[lIndex],height[rIndex]))
return maxH