11. 盛最多水的容器(javascript)11. Container With Most Water

该篇博客探讨了一个经典的计算机科学问题,即如何通过双指针法找到两条线段,使得它们与x轴形成的容器能容纳最多的水。示例展示了输入数组高度为[1,8,6,2,5,4,8,3,7]时,最大水量为49。博主提供了两种优化过的解题代码,核心是更新最大值并根据高度较小的一边移动指针。
摘要由CSDN通过智能技术生成

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

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

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

说明:你不能倾斜容器。

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

示例 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

解题思路参考:官方解题

双指针,Math.min(height[l], height[r]) * (r - l)计算体积公式
max 用于保存最大值

var maxArea = function (height) {
    let max = 0
    let l = 0, r = height.length - 1
    while (l < r) {
        let res = Math.min(height[l], height[r]) * (r - l)
        max = Math.max(max, res)
        if (height[l] > height[r]) {
            r--
        } else {
            l++
        }
    }
    return max
};
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
	//代码优化,减少使用一些变量可以提高性能
    let max = 0
    let l = 0, r = height.length - 1
    while (l < r) {
        max = Math.max(max, Math.min(height[l], height[r]) * (r - l))
        height[l] > height[r] ? r-- : l++
    }
    return max
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值