题目:Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
题意:给定多个二元组(i, ai),以(i, 0), (i ,ai)作为一个挡板的起点和终点,多个二元组(i, ai)可以表征多个挡板。在其中选取两个挡板和x轴作为一个容器,求所有容器中容量的最大值。
题解:首先给出选定两个挡板时求容量的公式V(i, j) = min(height[j], height[i]) * (j - i); (i < j)。先判断挡板数,小于2时不能形成容器,返回0。取左右边界两个挡板求第一个容量值。这时候,往中间扫描,为了保证结果正确,应该移动较低的挡板k。往中间寻找下一个比k高的挡板更新答案,最终 i >= j时结束。
代码如下:
classSolution:defmaxArea(self, height):"""
:type height: List[int]
:rtype: int
"""
l = len(height)
if l < 2: return0
i = 0
j = l - 1;
Max = min(height[i], height[j]) * (j - i)
while i < j:
if height[i] < height[j]:
while height[i+1] < height[i]:
i = i + 1
i = i + 1
Max = max(Max, min(height[i], height[j]) * (j - i))
else:
while height[j-1] < height[j]:
j = j - 1
j = j - 1
Max = max(Max, min(height[i], height[j]) * (j - i))
return Max