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.
意思是有n个非负整数a1, a2, ..., an,组成了n条两端为(i, ai) 和 (i, 0) 的垂线,找出两条线段和x轴组成的能盛最多水的容器,求最大容量.不能倾斜容器.
如有一组数[1, 2, 3, 2],所能组成的最大容量为4
首先用了两侧for循环,O(n^2),不出所料的超时了
public int maxArea(int[] height) {
if(height.length <= 1)
return 0;
int max = 0;
int container = 0;
for(int i = 1; i < height.length; i++) {
for(int j = 0; j <= i - 1; j++) {
container = Math.min(height[i], height[j]);
if(container * Math.abs(i - j) > max) {
max = container * Math.abs(i - j);
}
}
}
return max;
}
在网上看到一个O(n)的,想法是从两头往中间找有可能是最大的容器,容器的容量取决于小的线段,往中间移动时舍弃小的线段.
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int max = 0;
int container = 0;
while(right > left) {
container = (right - left) * Math.min(height[right], height[left]);
max = container > max ? container : max;
if(height[right] > height[left])
left++;
else
right--;
}
return max;
}