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.
代码如下:(方法一:超时)
public class Solution {
public int maxArea(int[] height) {
int max=0;
for(int i=0;i<height.length-1;i++)
{
int min=height[i];
for(int j=i+1;j<height.length;j++)
{
if(min>height[j])
min=height[j];
if(min*(j-i)>max)
max=min*(j-i);
}
}
return max;
}
}
代码如下:(方法二:Accept)
public class Solution {
public int maxArea(int[] height) { int left=0,right=height.length-1;
int max=Math.min(height[0],height[height.length-1])*(right-left); while(left<right)
{
if(height[left]<=height[right])
{
if(height[left]*(right-left)>max)
max=height[left]*(right-left);
left++;
}
else{
if(height[right]*(right-left)>max)
max=height[right]*(right-left);
right--;
}
}
return max;
}
}