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.
题是leetcode上看到的,是说给你一个数组,非负整形的,这些数值都能在坐标系中以点的形式表示出来。比如说:
[1,3,1,8,3],这里面数组里值的位置作为横坐标,值代表纵坐标, 形成的点就是(1.1) (2,3) (3,1) (4,8) (5,3), 每个点和x轴连线,任意两根线和x轴就形成了一个容器,求容器的最大水容量。容器不能倾斜
naive的办法就是2个循环嵌套,把任意两个值都试一遍,时间是O(n^2),显然时间太长
其实linear的时间就可以完成,代码如下:
public static int maxArea(int[] height){
int maxH=0;
int equation=0;
int i=0,j=height.length-1;
while(i!=j){
int edge=Math.min(height[i],height[j]);
equation=(edge)*(j-i);
maxH=Math.max(maxH,equation);
if(height[i]<height[j]) i++;
else j--;
}
return maxH;
}