lc11. Container With Most Water

180 阅读1分钟
  1. Container With Most Water Medium

4240

489

Favorite

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

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7] Output: 49

类型:Array

思路:木桶问题,从左右两边开始比较list[l],list[r], 以min值为边界的木桶,在剩下的遍历里面积是最大的, 比如[1,2,3,4,5,6,7,8,9],以1为边,最大值为8, 所以计算下newArea,去除,l++,继续遍历,max(area,newArea)

代码:python3

class Solution:
    def maxArea(self, height: List[int]) -> int:
        area,l,r=0,0,len(height)-1
        while l<r:
            newArea=0
            if height[l]<height[r]:
                newArea=(r-l)*height[l]
                l=l+1
            else:
                newArea=(r-l)*height[r]
                r=r-1
            area=max(area,newArea)
        return area

类似 leetcode.com/problems/tr…