https://leetcode-cn.com/problems/container-with-most-water/

python
python展开代码class Solution:
    def maxArea(self, height) -> int:
        l, r = 0, len(height) - 1  # 左右指针
        ans = 0
        while l < r:  # 左右指针指向同一个元素的时候退出循环
            area = min(height[l], height[r]) * (r - l)  # 面积 = 最短挡板 × 间距
            ans = max(ans, area)  # 答案只想要最大的面积
            if height[l] <= height[r]:  # 左挡板 小于 右挡板
                l += 1  # 左指针移动
            else:
                r -= 1  # 右指针移动
        return ans
print(Solution().maxArea([3, 5, 4]))
左右指针正确性:
(1)假设左指针指着height[0]不动;
(2)移动可行性:右指针指着height[-1],此时面积假设为area1。如果右指针移动,指着height[-2],此时面积假设为area2。间距的缩小,使得只有当height[-2]挡板大于之前的,才有可能找到更大的值。
(3)该移动哪一个指针?:左挡板 小于等于 右挡板,那么就移动左指针。


本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!