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.
题目的意思是横坐标上从i=0到i=size-1每个地方有一条垂直于横坐标的线段,参数中的数组就是这些线段的长度。某两个线段和横坐标围成一个二维容器,也就是一个面积,求这个容器的最大容量。
错误解法1:两层循环,遍历所有情况找到最大值,结果超时了。
错误解法2:优化方法1,i为从左往右搜索的指针,j为从右往左的指针,对于每一个i,记录当前j搜索到位置前面,也就是右边的最大线段长度,如果当前线段长度小于这个长度,显然不可能求出最大值,直接进行下一次循环(内层);外层循环同理。结果仍然超时。
正确解法1:贪心算法,为了使容器宽度最大,i,j分别从左从右搜索,为了使容器高度尽量高,如果height[i]>height[j],就j--;因为这样才可能使较短的那个线段更长,否则i++。
int maxArea(int* height, int heightSize) {
int i,j;
int max=0;
int currentArea;
i=0;
j=heightSize-1;
while(i!=j)
{
if(height[i]>height[j])
{
currentArea=(j-i)*height[j];
if(currentArea>max)
max=currentArea;
j--;
}
else
{
currentArea=(j-i)*height[i];
if(currentArea>max)
max=currentArea;
i++;
}
}
return max;
}