题解 | 盛水最多的容器

盛水最多的容器

https://www.nowcoder.com/practice/3d8d6a8e516e4633a2244d2934e5aa47

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param height int整型一维数组 
# @return int整型
#
class Solution:
    def maxArea(self , height: List[int]) -> int:
        n = len(height)
        # 当数组长度小于 2 时,不能形成容器,返回 0
        if n < 2:
            return 0
        # 初始化最大容量为 0
        max_water = 0
        # 左指针指向数组的第一个元素
        left = 0
        # 右指针指向数组的最后一个元素
        right = n - 1
        while left < right:
            # 计算当前容器的宽度
            width = right - left
            # 计算当前容器的高度,取两个指针所指元素的较小值
            current_height = min(height[left], height[right])
            # 计算当前容器的容量
            current_water = width * current_height
            # 更新最大容量
            max_water = max(max_water, current_water)
            # 如果左指针所指元素较矮,将左指针右移一位
            if height[left] < height[right]:
                left += 1
            # 否则,将右指针左移一位
            else:
                right -= 1
        return max_water
                

全部评论

相关推荐

昨天 18:43
门头沟学院 Java
是暑期都招满了吗
投递腾讯等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务