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.
题意大概是:给一个数组height[n],其中每一个元素height[i]=num,i代表它的横坐标,num代表纵坐标,要求由这个数组任意两个元素围成的面积最大的。 可以想象,如果最大由【i,j】对应构成,假设i<j,那么,i左边的所有元素高度都应当小于i 对应的高度,j右边所有元素高度都应该低于j对应的高度。所以可以从数组两边开始收缩,高度小的那边开始向中间收缩,直到找到一个高度比它高的才停止。
int maxArea(int* height, int heightSize) { int maxarea = -1,area,head=0,tail=heightSize-1,p; while(head<tail){ area = (height[head]<height[tail]?height[head]:height[tail])*(tail-head); maxarea = maxarea>area?maxarea:area; if(height[head]<height[tail]){ p = head; while(head<tail&&height[head]<=height[p]) head++; } else{ p = tail; while(head<tail&&height[tail]<=height[p]) tail--; } } return maxarea; }