LeetCode 11. 盛最多水的容器

11. 盛最多水的容器

Difficulty: 中等

给你 n 个非负整数 a<sub style="display: inline;">1</sub>,a<sub style="display: inline;">2,</sub>...,an每个数代表坐标中的一个点 (i, a<sub style="display: inline;">i</sub>) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, a<sub style="display: inline;">i</sub>)(i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器。

示例 1:

输入:[1,8,6,2,5,4,8,3,7]
输出:49 
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例 2:

输入:height = [1,1]
输出:1

示例 3:

输入:height = [4,3,2,1,4]
输出:16

示例 4:

输入:height = [1,2,1]
输出:2

提示:

  • n = height.length
  • 2 <= n <= 3 * 10<sup>4</sup>
  • 0 <= height[i] <= 3 * 10<sup>4</sup>

Solution

Language: 全部题目

这是一道双指针题。可以证明,当我们往中心方向移动双指针中指向数较大的那个指针,无论该指针怎么移动,所得到的结果一定小于等于先前的,所以只能移动双指针中指向数较小的那个指针,并且是往中心方向移动。

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r = 0, len(height)-1
        res = 0
        while l < r:
            area = min(height[l], height[r]) * (r-l)
            res = max(area,res)
            if height[l] <= height[r]:
                l += 1
            else:
                r -= 1
        return res
原文地址:https://www.cnblogs.com/swordspoet/p/14048385.html