题目: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.
解题思路:可以想象,一个满足题意的答案,既需要宽度比较大,也需要高度比较大。我们从最宽的宽度开始,选择最左边和最右边组成的容器大小为初始值,然后沿着X轴慢慢缩小。这过程中,要使得组成的容器体积要比初始值大,那么需要它的高度要比之前的边高才行。
代码如下:
int maxArea(vector<int>& height) {
int water = 0;
int i = 0, j = height.size() - 1;
while (i < j) {
int h = min(height[i], height[j]);
water = max(water, (j - i) * h);
while (height[i] <= h && i < j) i++;
while (height[j] <= h && i < j) j--;
}
return water;
}