zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    树的前序 中序 后序遍历
    算法入门经典-第四章 例题4-3 救济金发放
    算法入门经典-第五章 例题6-10 下落的树叶
    排序(三) 选择排序

    printf格式输出总结
    并查集
    异或的应用
    ActionContext详解
    ActionContext表格总结
  • 原文地址:https://www.cnblogs.com/waterr/p/13800522.html
Copyright © 2011-2022 走看看