Leetcode 11. Container With Most Water The Solution of Python

来源:互联网 发布:mac 安装sass 编辑:程序博客网 时间:2024/06/06 21:39

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.

Python:

class Solution(object):    def maxArea(self, height):        """        :type height: List[int]        :rtype: int        """        i,j,Max=0,len(height)-1,0 #用来定义最大盛水量的两板位置和水量        while i!=j:            if height[i]>=height[j]:#计算每一次的水量,并移动短板                mid,j=(j-i)*height[j],j-1            else:                mid,i=(j-i)*height[i],i+1            Max=max(Max,mid)#用max存放最大水量        return Max

容器的水量由最短板和两板距离决定,可行的方法是计算任意两板的盛水量,但是这样太冗余,因此按上述算法来计算。

0 0