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
    

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

  • 相关阅读:
    简单编码解码学习
    如何把SQLServer数据库从高版本降级到低版本?
    快速读取csv平面文件,并导入数据库,简单小工具
    数据流处理数据
    配置文件的几种读取方式
    常用webservice接口地址
    路径转换
    Tornado与JS交互工作
    测试技术发展之我见
    移动测试人员的未来:测试开发技术的融合
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9781842.html
Copyright © 2011-2022 走看看