Container With Most Water

Posted phinza

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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])


以上是关于Container With Most Water的主要内容,如果未能解决你的问题,请参考以下文章

11 Container With Most Water

LeetCode11-Container With Most Water

LeetCode11. Container With Most Water 解题报告

Container with most water

Container With Most Water

Container With Most Water