1. FlyPython首页
  2. 数据结构与算法
  3. leetcode题解

「LeetCode每日一题」—— 11. 盛最多水的容器

11. 盛最多水的容器

链接:https://leetcode-cn.com/problems/container-with-most-water/
难度:中等

题目

思路

这道题和第35天——42. 接雨水是很类似的题。我们也采用双指针来做。

左右的指针,要停止的话,他们之间的最小距离至少是1,因为需要有空间,不能重合。那看看怎么移动呢。

我们可以这个看成一个求矩形的最大面积,开始指针在两端 ,长肯定是最长,但是宽不一定是,而且宽只能依照两个指针当前值中的最小值。要想矩形面积最大,我们可以把这个最小值的指针往中间移动,移动的过程中保存面积最大值即可。

74674644b50be01eaa56186a897ef46b.png

方案代码

解决方案:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        i, j, res = 0, len(height) - 1, 0
        while i < j:
            if height[i] < height[j]:
                res = max(res, height[i] * (j - i))
                i += 1
            else:
                res = max(res, height[j] * (j - i))
                j -= 1
        return res

原创文章,作者:flypython,如若转载,请注明出处:http://flypython.com/algorithm/leetcode/335.html