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.
解法思路:这道题其实求不规则矩形的最大长方形面积,依然是贪心算法,我们首先计算出首尾相连的矩形的长方形面积,因为这是长最大的矩形的面积,接下来我们想找到这最优解的话,肯定是要向中间移动,而这移动必然使得长度减少,那么只有高度增高,才能使得面积更大;因此我们找出更高的最小高,所以要分为两种情况,当左边的高低于右边的高,我们必然使得,左边的点向右移,找到第一个比他高的边,使得面积更大,左边高于右边时,同理,同理左边移动,找到更高的边;
class Solution {
public:
int maxArea(vector<int>& height) {
int containerWater = 0;
int pt,i,j;
int head = 0; int end = height.size()- 1;
while (end > head){
pt = min(height[head], height[end]);
containerWater = max(containerWater,pt*(end- head));
if(height[head] < height[end]) {
i = 1;
while(height[head] > height[head + i]) i++;
head += i;
}else{
j = 1;
while(height[end]> height[end-j]) j++;
end -= j;
}
}
return containerWater;
}
};
运行结果