leetcode 11. 盛最多水的容器

``````输入: [1,8,6,2,5,4,8,3,7]

``````int maxArea(vector<int>& height) {
int n=height.size();
if(n<2) return 0;

int ans=0;
for(int i=0;i<n-1;i++)
for(int j=i+1;j<n;j++)
ans=max(ans,(j-i)*min(height[i],height[j]));

return ans;
}``````

``````int maxArea(vector<int>& height) {
int n=height.size();
if(n<2) return 0;
//初始木板分别取最左和最右，计算初始容量
int i=0,j=n-1;
int ans=min(height[i],height[j])*(j-i);
//容量可能继续增大吗？
while(i<j)
{
//考察较短的木板，把它变长，再比较容量
if(height[i]<height[j])
{
//左边短则左板右移
int temp=height[i++];
while(i<n && height[i]<temp) i++;
ans=max(ans, (j-i)*min(height[i],height[j]));
}
else
{
//右边短，或者一样长，则右板左移
int temp=height[j--];
while(j>i && height[j]<temp) j--;
ans=max(ans, (j-i)*min(height[i],height[j]));
}
}
return ans;
}``````

``````int maxArea(vector<int>& height) {
int max1=0,l=0,r=height.size()-1;
while(l<r)
{
max1=max(max1,(r-l)*min(height[r],height[l]));
if(height[l]<height[r])
l++;
else r++;
}
return max1;
}``````

``````int maxArea(vector<int>& height) {
int i=0,j=height.size()-1;
int ans=0,shorter=0;
while(i<j)
{
ans=max(ans, (j-i)*min(height[i],height[j]));
if(height[i]<height[j])
{
shorter=height[i++];
while(i<j && height[i]<shorter) i++;
}
else
{
shorter=height[j--];
while(j>i && height[j]<shorter) j--;
}
}
return ans;
}``````

;