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.
根据一个数组计算两条线所包含的最大面积。
用两个指针,分别指向数组两端。
计算当前两条线段所包含的面积后,将较短的一条线段像中间移动。
因为短的线段已经用“满”了,也就是说,即使长的线段像中间移动,获得更长的线段,包含的面积也不可能增加了(面积计算受短线段限制)。
当然代码还可以用max()等方法简写,不再讨论。
class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height)-1
final=0
while l<r:
if height[l]<height[r]:
area=height[l]*(r-l)
l+=1
else:
area=height[r]*(r-l)
r-=1
if area>final:
final=area
return final