码迷,mamicode.com
首页 > 其他好文 > 详细

Container With Most Water

时间:2019-08-24 09:36:23      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:most   find   lin   src   HERE   idt   case   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])


Container With Most Water

标签:most   find   lin   src   HERE   idt   case   water   原来   

原文地址:https://www.cnblogs.com/phinza/p/11403385.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!