zoukankan      html  css  js  c++  java
  • 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
    

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

  • 相关阅读:
    1740-约数之和
    1653-南邮的面积
    1880-A. 偷吃可耻
    1429-全排列的输出
    1342-皇后控制问题
    1340-逆矩阵问题
    1319-n皇后问题
    1221-最少硬币问题
    1219-整数因子分解问题
    linux 命令小结
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9781842.html
Copyright © 2011-2022 走看看