leetcode--盛最多水的容器

给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (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 * 104

0 <= height[i] <= 3 * 104

来源:力扣(LeetCode)

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

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


代码实现如下:

public int maxArea(int[] height) {

if (height ==null || height.length ==0) {

return 0;

    }

if (height.length ==1) {

return height[0];

    }

int head =0;

    int tail = height.length  -1;

    int max = calculate(height, head, tail);

    while (head < tail) {

if (height[head] < height[tail]) {

head++;

        }else {

tail--;

        }

max = Math.max(calculate(height, head,tail), max);

    }

return max;

}

private int calculate(int[] height, int head, int tail) {

if (height[head] > height[tail]) {

return height[tail] * (tail -head);

    }else {

return height[head] * (tail -head);

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容