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.
题意:给定n条线段,第i条线段的两个端点是(i,0)和(i,ai),这n条线段都是垂直于x轴的,选取其中的两条线段,使这两条线段和x轴构成的容器能容纳的水最多。
方法一:两层循环时间复杂度为O(n^2),但肯定会超时
方法二:
参考:http://blog.csdn.net/a83610312/article/details/8548519
容积即面积,它受长和高的影响,当长度减小时候,高必须增长才有可能提升面积,所以从长度最长时开始递减,然后寻找更高的线来更新候补;
假设我们找到能取最大容积的纵线为 i , j (假定i
class Solution(object):
def maxArea(self, height):
n=len(height)
if n<2:
return 0
i=0 #左边
j=n-1 #右边
con=0 #容积
while i<j:
minline=min(height[i],height[j]) #最小边
con=max(minline*(j-i),con)
if height[i]<=height[j]:
k=i
while height[k]<=height[i] and k<j:
k+=1
i=k
else :
k=j
while height[k]<=height[j] and k>i:
k-=1
j=k
return con