11. Container With Most Water

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.python

Note: You may not slant the container and n is at least 2.code

能裝最多水的容器是多大?  這裏s=(j-i)*min(a[i],a[j])
orm

方法一,暴力搜索 for i range(n): for j in range(i+1,n):ip

方法二,從兩邊往中間夾,假設最開始(0,3)(10,4)兩個點(start,end),要比這個容器大,必定不包括(0,3)這個點。get

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        l=0
        r=len(height)-1
        maxarea=0
        while l<r:
            Area=min(height[l],height[r])*(r-l)
            if maxarea<Area:
                maxarea=Area
            if height[l]>height[r]:   
                r-=1
            else:
                l+=1
        return maxarea
相關文章
相關標籤/搜索