011 Container With Most Water

 
 

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.




题目的意思是:

 有n个高度不同的数作为为Y坐标,以序列1到n为X坐标,这样的点(i,ai)分别和(i,0)组成的线段有n条,从中选取两条,以最短的一条为高,线段在X轴上的距离为宽,求最大的矩形面积。


时间复杂度为O(n)

解题思路:两条线段,哪个短,就换哪个

int maxArea(int* height, int heightSize) {
	int i,j,max,area;
	i=0;
	j=heightSize-1;
	max=0;
    while(i<j){
    	area=(height[i]>height[j]?height[j]:height[i])*(j-i);
    	if(area>max){
    		max=area;
    	}
    	if(height[i]>height[j]){
    		j--;
    	}else{
    		i++;
    	}
    }
    return max;
}







你可能感兴趣的:(011 Container With Most Water)