题目
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个坐标(i,ai)(i,0),与X轴垂直的多条线段,要找到两个线段之间组成的容器盛水量最大。
加入每两个线段计算一下,会超时。
先计算首尾两条线段之间的盛水量,然后左边跳过更小的边,右边跳过更小的边,再次计算,直到找到最大值。因为向中间回笼的过程中,由于宽度变小,更低的边带来的盛水量会更少,因此略去。
下面的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;
}