leetcode 11
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 and n is at least 2.
思路:題目要求是x軸上在1,前翎,2...n點(diǎn)上有許多垂直的線段稚配,長度依次是a1,a2...an.找出兩條線段港华,使他們和x軸圍成的面積最大道川。
弄兩個(gè)指針l和r,從頭尾開始立宜,如果height[l]<height[r],在往中間移動的過程中x軸即底是變小的冒萄,所以只能讓低的height變化面積才會有變化,變高的話就更新面積橙数,不變的話就不更新面積尊流,更新后將l++,反之r--灯帮。
var maxArea = function(height) {
var l=0;
var r=height.length-1;
var res=Math.min(height[l],height[r])*(r-l);
while(l<r){
if(height[l]<height[r]){
res=Math.max(res,(r-l)*height[l])
l++;
}else{
res=Math.max(res,(r-l)*height[r]);
r--;
}
}
return res;
};