Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
簡單來說就是給你一個數(shù)組,在以下標(biāo)位橫坐標(biāo)的x軸上畫垂直于x軸的線,這個線的高度就是數(shù)組的值。用這些線來組成水槽,找到盛水最多的。
使用兩個指針,指向開頭和結(jié)尾,找到矮的那個,把指向它的指針往中間挪一個。
因為此時不管這個矮的和剩下的誰配,盛的水都不會比現(xiàn)在多,高度不會變,長度會變小。所以這個矮的就再也不用找了。
var maxArea = function(height) {
var max = 0;
var l = 0;
var r = height.length;
while (l<r) {
var now;
if (height[l]<height[r]) {
now = height[l] * (r-l);
l++;
} else {
now = height[r] * (r-l);
r--;
}
max = now > max ? now : max;
}
return max;
};