题目:
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, 其中的第i位与第i位的值(i, height[i])是坐标平面上的一个点,它与x轴做垂直线,这样就形成了i个垂直于x轴的线,假设这些是盛水的段短,求任意两个短板间水的容量最大值。
使用双层循环实现,但当数组很大时就 Time limited Exceeded。
public static int maxArea(int[] arr){
int end=arr.length-1,max=0,temp=0;
for(int i=0;i<end;i++){
for(int j=i;j<end;j++){
temp=Math.min(arr[i], arr[j])*(j-i);
max=max>temp?max:temp;
}
}
return max;
}
解决方法:取最左边的为left,最右边的为right,所有可能比这种大的情况只能是这两个高度较小的那一端向中间移动。一直循环这个动作,最大值肯定在其中。
public static int maxArea(int[] height) {
int start=0,end=height.length-1,max=0,temp=0;
while(start<end){
temp=Math.min(height[start], height[end])*(end-start);
max=max>temp?max:temp;
if(height[start]>height[end])
end--;
else
start++;
}
return max;
}