题目描述
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.
给定 n 个正整数 a1,a2,...,an,其中每个点的坐标用(i, ai)表示。 画 n 条直线,使得线 i 的两个端点处于(i,ai)和(i,0)处。请找出其中的两条直线,使得他们与 X 轴形成的容器能够装最多的水。
注意:你不能倾斜容器,n 至少是2。
解题思路:
这道题其实和42雨水题差不多,这道题也是从两边向中间遍历,找到最大的那个容器即可.
实现代码:
class Solution {
public:
int maxArea(vector<int> &height) {
int lpoint = 0, rpoint = height.size() - 1;
int area = 0;
while (lpoint < rpoint)
{
area = max(area, min(height[lpoint], height[rpoint]) * (rpoint - lpoint));
if (height[lpoint] > height[rpoint])
rpoint--;
else
lpoint++;
}
return area;
}
};