題目
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.
分析
給了n個(gè)坐標(biāo)(i,ai)(i,0),與X軸垂直的多條線段,要找到兩個(gè)線段之間組成的容器盛水量最大。
加入每兩個(gè)線段計(jì)算一下,會超時(shí)。
先計(jì)算首尾兩條線段之間的盛水量,然后左邊跳過更小的邊,右邊跳過更小的邊,再次計(jì)算,直到找到最大值。因?yàn)橄蛑虚g回籠的過程中,由于寬度變小,更低的邊帶來的盛水量會更少,因此略去。
下面的C代碼已通過。
int maxArea(int* height, int heightSize) {
int i=0,j=heightSize-1;
int ans=0,temp=0,min=0;
while(i<j)
{
if(height[i]<height[j])min=height[i];
else min=height[j];
temp=min*(j-i);
printf("%d\n",temp);
if(temp>ans)ans=temp;
while(i<j&&height[i]<=min)i++;
while(i<j&&height[j]<=min)j--;
}
return ans;
}