美文网首页
11. 盛最多水的容器

11. 盛最多水的容器

作者: 滨岩 | 来源:发表于2020-11-14 00:07 被阅读0次

给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器。

示例 1:

image.png

输入:[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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    public int maxArea(int[] height) {
        int l = 0;
        int r = height.length - 1;

        int max = (r - l) * Math.min(height[l], height[r]);
        while (l < r) {

            //移动一格 宽度肯定会减少
            //移动短板,面积才有机会增加
            //移动长板,面积不会比以前的面积大
            if (height[l] < height[r]) {
                l++;
                int area = (r - l) * Math.min(height[l], height[r]);
                max = Math.max(max, area);
            } else {
                r--;
                int area = (r - l) * Math.min(height[l], height[r]);
                max = Math.max(max, area);
            }
        }
        return max;
    }

相关文章

网友评论

      本文标题:11. 盛最多水的容器

      本文链接:https://www.haomeiwen.com/subject/ppkibktx.html