Leetcode011 container-with-most-water

盛最多水的容器

题目描述:

给定 n 个非负整数 a1a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明: 你不能倾斜容器,且 n 的值至少为 2。

图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。此情况下,容器能容纳水的最大值为 49。

示例 :

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

解题思路:

我们可以把盛水的容器的两块板分为左板、右板。假设左板高度为h,且比右板低,两块板之间的距离为w,则此时最多能装水 w h w*h ,此时我们尝试移动隔板。如果将左板向右移,那么可能使容积变大,例如,左板的右边板子高h1(还是比右板低),此时最多装水 ( w 1 ) h 1 (w-1)*h1 ,有可能比 w h w*h 大;如果将右板向左移,由于水的高度不能高于左板,所以容积最多为 ( w 1 ) h (w-1)*h ,肯定比 w h w*h 小。当然,同样的道理,如果右边的板子比左边的低,那就向左移动右边的板子。
基于上面的假设,我们只要把两块隔板依次向中间靠拢,就可以求出最大的容积。


Python源码:

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        max_area = 0
        left = 0
        right = len(height) - 1
        while right > left:
            max_area = max(max_area, min(height[left], height[right]) * (right - left))
            if height[right] > height[left]:
                left += 1
            else:
                right -= 1
        return max_area

欢迎关注我的github:https://github.com/UESTCYangHR

猜你喜欢

转载自blog.csdn.net/dzkdyhr1208/article/details/89088123