[Array]011 Container With Most Water

  • 分类:Array

  • 考察知识点:Array(数组遍历) 动态规划

  • 最优解时间复杂度:O(n)

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.

Example:

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

这道题最优的解法就是动态规划,一方面找到那一条最长的轴,一方面遍历数组。

代码:

最优解法:

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        L,R,width,res=0,len(height)-1,len(height)-1,0
        for w in range(width,0,-1):
            if height[L]<height[R]:
                res=max(res,height[L]*w)
                L+=1
            else:
                res=max(res,height[R]*w)
                R-=1
        return res

讨论:

1.这个题目最傻的方法让人是两个for循环,这个不用说
2.这个题感觉还是用到了动态规划,一方面是去找它的那条最长轴,一方面算它的最大面积。

WechatIMG1580.jpeg

这个题要用动态规划思路,我觉得我还应该再强化一下。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • 马上要过年了, 家里开始了大扫除, 擦玻璃,擦家俱,扫墙角,涮油烟机,拖地面……打扫卫生就要像这样,无死角! 终于...
    todayafter阅读 302评论 7 1
  • 我喜欢读书是从小时候读“闲书”开始的。所谓“闲书”,实际上就是课外书籍。读这类书,常被那时的老师、家长们斥之为“不...
    我是hdc阅读 400评论 0 1
  • 热潮经久不衰 2017年考研于昨天正式打响,全国考研人数预计突破170万,除个别年份外,报名人数和招生人数均年年攀...
    梅庄少主阅读 461评论 0 2
  • 楼下排队,让本仙女开心开心❤
    爱德华筱鱼儿阅读 91评论 0 0