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.
思路
首先假设我们找到能取最大容积的纵线为 i , j (假定i<j),那么得到的最大容积 C = min( ai , aj ) * ( j- i)
有两个指针i和j分别指向头和尾, 如果a[i]<a[j], 则i++,否则j--:
因为
假设k>i,a[i]<a[j]
要使得(k,h)容积min(a[k],a[j])*(j-k)>min(a[i],a[j])*(j-i),则a[k]必须大于a[i];
若a[k]<a[i],则(k,j)容积min(a[k],a[j])*(j-k)肯定比(i,j)容积min(a[i],a[j])*(j-i)小;
所以此种情况移动j只能得到更小的值,移动j无用,只能移动i。反之亦然。
public class Solution {
public int maxArea(int[] height) {
if(height.length<1){
return 0;
}
int i=0;
int j=height.length-1;
int area=0;
int tmp;
while(i<j){
if(height[i]<height[j]){
tmp=height[i]*(j-i);
i++;
}else{
tmp=height[j]*(j-i);
j--;
}
if(area<tmp){
area=tmp;
}
}
return area;
}
}