0
点赞
收藏
分享

微信扫一扫

11.盛最多水的容器

小编 2022-02-12 阅读 64

在这里插入图片描述
第一次很难想到双指针的解法,参考链接 盛最多水的容器(双指针,清晰图解)
双指针容易实现,问题是为什么双指针最后的结果能保证容器盛的水最多?

  • 证明:
    在这里插入图片描述

代码如下:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        # 双指针解法
        left, right = 0, len(height) - 1 # 题目保证了height至少有两个值
        res = 0
        while left < right:
            if height[left] < height[right]:
                res = max(res, (right - left) * height[left]) # 更新最大面积,当前面积计算公式(right - left)(底边宽度) * height[left](短板高度)
                left += 1 # 可惜python不能直接left++,不然还可以更加简洁
            else:
                res = max(res, (right - left) *height[right])
                right -= 1
        
        return res
举报

相关推荐

0 条评论