力扣11-JS盛最多水的容器

给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。

找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

返回容器可以储存的最大水量。

说明:你不能倾斜容器。

力扣11-JS盛最多水的容器

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
    let res = 0, i = 0, j = height.length - 1;
    while (i < j) {
        res = Math.max(res, Math.min(height[i], height[j]) * (j - i))
        if (height[i] < height[j]) {
            i++
        } else {
            j--
        }
    }
    return res
}
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
    let maxArea = 0;
    let left = 0;
    let right = height.length - 1;

    while (left < right) {
        const currentArea = Math.min(height[left], height[right]) * (right - left);
        maxArea = Math.max(maxArea, currentArea);

        if (height[left] < height[right]) {
            left++;
        } else {
            right--;
        }
    }

    return maxArea;
};

 

原创文章,作者:czhdawn,如若转载,请注明出处:https://www.czhdawn.cn/archives/4896

(0)
czhdawn的头像czhdawn
上一篇 1天前
下一篇 2024年3月19日 13:32

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注