1. 题目
011- Container With Most Water
2. 算法
双指针:O(n)
算法
最大盛水量取决于两边中较短的那条边,而且如果将较短的边换为更短边的话,盛水量只会变少。所以我们可以用两个头尾指针,计算出当前最大的盛水量后,将较短的边向中间移,因为我们想看看能不能把较短的边换长一点。这样一直计算到左边大于右边为止就行了。
3. 代码
class Solution{
public:
int maxArea(vector<int> &height){
int res=0,n=height.size();
int left=0,right=n-1;
while(left<right){
res=max(res,(right-left)*min(height[left],height[right]));
if(height[left]<height[right])
left++;
else
right--;
}
return res;
}
};