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 and
n is at least 2.
做法一:假设某次找到的桶的有效高度为h,那么我们只需要找这个桶的宽度即可,最宽的宽度为n,唯一可能缩小这个宽度的可能性是数组最开始或者最末尾有连续的小于h的木板,使得桶宽度减小。
int maxArea(vector<int>& height) {
int maxwater=0;
int n=height.size();
int low=0,high=n-1;
int len=n-1,h=1;
int highest=0;
for(int i=0;i<n;i++)highest=max(highest,height[i]);
while(h<=highest){
while(height[low++]<h)len--;
while(height[high--]<h)len--;
if(len>=0)maxwater=max(maxwater,len*h);
h++;
len=n-1;
low=0,high=n-1;
}
return maxwater;
}
做法2:做法2是做法1的一种优化,不用从高度最小的桶开始找起,而是直接先查看宽度最宽的桶的容量,然后从两头开始缩小桶的宽度,倘若遇到容量比这个还小的,就继续移动,否则就比较。
int maxArea(vector<int>& height) {
int maxwater=0;
int n=height.size();
int low=0,high=n-1;
int h=0;
while(low<high){
h=min(height[low],height[high]);
maxwater=max(maxwater,h*(high-low));
while(low<high&&height[low]<=h)low++;
while(low<high&&height[high]<=h)high--;
}
return maxwater;
}