Python算法_盛最多水的容器(04)

给你 n 个非负整数 a1,a2,...,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

 

class Solution:
    def maxArea(self, height: List[int]) -> int:
        height = list(enumerate(height))
        maxArea_list = []
        left, right,left_idx, right_idx = height[0][1], height[-1][1], 0, height[-1][0]

        while True:
            smaller = min(left, right)
            area = smaller * (right_idx - left_idx)
            maxArea_list.append(area)

            n = 0 if left < right else 1
            before = right_idx - left_idx

            for i in height[left_idx + 1:right_idx][::(-1)**n]:
                if i[1] > smaller:
                    if n == 0:
                        left, left_idx = i[1], i[0]
                        break
                    else:
                        right, right_idx = i[1], i[0]
                        break
            after = right_idx - left_idx
            
            if after - before == 0:
                return max(maxArea_list)

 

posted @ 2020-10-12 00:29  止一  阅读(274)  评论(0编辑  收藏  举报