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.
这道题就是一个在第一象线有多个竖线,竖线长度就是高。两条竖线之间距离就是底。求最大面积。不过由于水桶原理,最大面积是由最短的竖线决定的。同时,我们还要考虑底。因为S=底*高。
方法是从两边开始查找,我们尽量要找两条竖线都很高,并且竖线之间距离很远的组合。所以对于中间低的竖线并且近的竖线可以不计算。每次计算完,更新max就可以了。
我写的原始版本:
class Solution {
public:
int maxArea(vector<int>& height) {
const int size = height.size();
if(size < 2)
return 0;
int l = 0, r = size - 1;
int res = 0;
for(int i=0, j=size-1; i<j; ) {
if(height[i] > height[l])
l = i;
if(height[j] > height[r])
r = j;
res = std::max(res, std::min(height[i], height[j]) * (r-l));
if(height[i] < height[j])
++i;
else
--j;
}
return res;
}
};
精简版本:
class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0, j = height.size() - 1;
int res = 0;
while(i < j) {
int h = std::min(height[i], height[j]);
res = std::max(res, h * (j - i));
while(height[i] <= h && i < j) ++i;
while(height[j] <= h && i < j) --j;
}
return res;
}
};