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.
题意:
给出一个序列a1,a2,a3......an,每个数字ai表示在(i,0)(i,ai)之间有木杆,也就是一共有n个竖直木杆。我们选取其中两根木杆跟x轴可以构成一个凹形容器,问整个容器体积最大为多少?也就是求:Max(min(ai,aj)*abs(i-j)).
分析:
很显然如果使用两重循环,枚举两根木杆,很简单就可以解决这个问题。但是时间复杂度是O(n^2)。
所以我们需要换一种思路。
假设一开始两根木杆选取最左和最右。无论最优解为何值,我们只要将最左木杆右移,最右木杆左移,总能达到。
但是,是应该让最左木杆右移还是最右木杆左移呢?我们知道无论是left ++还是right -- ,对于abs(right - left) 值都是不变的。
变化的是min(aleft,aright)。所以根据贪心的思想,我们只需要判断left,right对应的两根木头哪个比较短,就移动哪个。然后不断更新最大值。
代码:
class Solution {
public:
int maxArea(vector<int>& height) {
int left,right,ans;
left = 0,right = height.size() - 1;
ans = min(height[left],height[right])*(right-left);
while(left<right){
if(height[left]<height[right]){
left ++;
}else{
right --;
}
if(min(height[left],height[right])*(right-left)>ans)ans = min(height[left],height[right])*(right-left);
}
return ans;
}
};