内容简介:给定说明:你不能倾斜容器,且
LeetCode11.盛最多水的容器 JavaScript
给定 n 个非负整数 a1,a2,...,an ,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2 。
图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7] 。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49 。
示例:
输入: [1,8,6,2,5,4,8,3,7]
答案参考:
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(height) {
let max = 0
for (let i = 0, j = height.length-1; i< j; ) {
// 因为容量受限于矮的一边,所以在向内收缩时,移动矮的一侧
// 如果新边足够高的话,效果有可能大于宽度收缩带来的负效果
let minHeight = height[i] > height[j] ? height[j--] : height[i++]
// 因为上面--或者++了,所有要补个+1
max = Math.max(max, (j-i+1)* minHeight )
}
return max
};
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Design for Hackers
David Kadavy / Wiley / 2011-10-18 / USD 39.99
Discover the techniques behind beautiful design?by deconstructing designs to understand them The term ?hacker? has been redefined to consist of anyone who has an insatiable curiosity as to how thin......一起来看看 《Design for Hackers》 这本书的介绍吧!