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.

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

avatar

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

Solution1:(TLE)

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        def search(a):
            res = 0
            for i in range(a):
                res = max((a-i)*min(height[a],height[i]),res)
            return res
        dp = [0 for _ in range(len(height))]
        dp[0] = 0
        dp[1] = min(height[0],height[1])
        for i in range(2,len(height)):
            dp[i] =max(dp[i-1],search(i))
        return dp[-1]

Solution2:

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        left,right = 0,len(height)-1
        res = 0
        while left<right:
            res = max(res,min(height[left],height[right])*(right-left))
            if height[left]>height[right]:
                right -= 1
            else:
                left += 1
        return res

一次遍历就可以了。因为决定面积的两个因素是长和宽。从两边向中间遍历已经保证了宽最大,只需要对长做一遍搜索就可以了。

原文地址:https://www.cnblogs.com/bernieloveslife/p/9781842.html