zoukankan      html  css  js  c++  java
  • Container With Most Water

    Given n non-negative integers a1, a2, ..., a, 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

    思路:
    最左与最右分别设置两个点:l,r,
    设它们的高为:hl,hr
    先记录一次面积:
    area = (r-l)*min(hl,hr)
    即为:两点间的距离*两者之间最矮的高度

    假设在l,r原始点之内仍有可能存在更大的面积组合:
    因为要往里找新的l,r组合,长度(r-l)是一直在缩小的,如果存在更大面积,则一定存在更长的高,则min(*hr,*hl)>min(hr,hl)
    假设一开始,hr > hl, area = (r-l) * hl ;如果存在更大面积, 则*hl > hr, *area = (r-*l) * hr,因hr > hl, *area有可能会大于原面积
    假设,hr < hl, area = (r-l) * hr ;如果存在更大面积, 则*hr > hl, *area = (*r-l) * hl, 因hl > hr, *area有可能会大于原面积

    如果hl == hr 怎么办?
    不断同时移动两个点,直到新的lr的高度同时大于原来的高度:
    因为r-l一直在缩小,min(hl,hr)必须变大,所以hr,hl要同时变大才,有机会超越原来的面积。

    class Solution(object):
        def maxArea(self, height):
            """
            :type height: List[int]
            :rtype: int
            """
            l,r = 0, len(height)-1
            box = [self.getarea(height, l, r)]
            
            while l < r:
                if l < r and height[l] < height[r]:
                    l += 1
                    if l < r and height[l] > height[l-1]:
                        box.append(self.getarea(height, l, r))
                if l < r and height[l] > height[r]:
                    r -= 1
                    if l < r and height[r] > height[r+1]:
                        box.append(self.getarea(height, l, r))
                if l < r and height[l] == height[r]:
                    now = height[l]
                    while l < r and now >= height[l]:
                        l += 1
                    while l < r and now >= height[r]:
                        r -= 1
                    box.append(self.getarea(height, l, r))
            return max(box)
                    
        def getarea(self, height, l, r):
            return (r-l)*min(height[l], height[r])


  • 相关阅读:
    最近出现很多数据库被攻击案例,在数据库中的文本型字段中加入了script代码
    深入线程,实现自定义的SynchronizationContext
    云计算 (转载)
    VS 2008和.NET 3.5 Beta2新特性介绍(转载)
    js对文字进行编码涉及3个函数
    Sharepoint,MOSS,多语言Webpart (.net2.0)
    Silverlight Toolkit
    Silverlight 2.0正式版下周发布
    搭建Silverlight2.0开发环境(转载)
    如何通过使用 SQL Server 中的 Detach 和 Attach 函数将 SQL Server 数据库移到新位置
  • 原文地址:https://www.cnblogs.com/phinza/p/11403385.html
Copyright © 2011-2022 走看看