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.
最开始没太懂题目,简单翻译一下:有n个数,在二维坐标上,任意挑选两个点,纵坐标和x轴组成了一个水桶,求最大的容积。如果是求容积最简单的就是底乘高,底为right-left,而装多少水取决于两个之间短的那个高度,之后相乘就是容积。
#include<math>
class Solution {
public:
int maxArea(vector<int>& height) {
int left=0;
int right=height.size()-1;
int maxarea=0;
while(left<right&&left>=0&&right<=height.size()-1)
{
maxarea=max(maxarea,min(height[right],height[left])*(right-left));
if(height[left]<height[right])
{
left++;
}
else
right--;
}
return maxarea;
}
};