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.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
简单来说就是给一堆高,问取哪两个高围的面积最大
思路1:暴力
没什么好说的 直接过一遍
#define MIN(A,B) A<B?A:B
int maxArea1(vector<int>& height) {
int sz = height.size(), res = 0, temp = 0;
for(int i=0;i<sz;++i)
for (int j = i + 1; j < sz; ++j) {
temp = (j - i)*(MIN(height[i], height[j]));
if (temp > res) res = temp;
}
return res;
}
思路2:优化
在上述暴力方法的基础上,寻找可以优化的地方
假设初始面积是取最左和最右两个高计算得到,从两边向中间扫描
每次选当前两高中较短的一边向另一边移动,计算面积并与之前值比较。
这样操作时因为,边移动时会使两边距离变小,而计算面积时是根据较短边的高度计算的,移动较长边不会得到任何收益(移动到更长边还是使用另一边高,移动到更短边会使面积再次减少)。
#define MIN(A,B) A<B?A:B
int maxArea(vector<int>& height) {
int j = height.size()-1, res = 0, temp = 0;
int i = 0;
while(i<j){
temp = (j - i)*(MIN(height[i], height[j]));
if (temp > res) res = temp;
height[i] > height[j] ? --j : ++i;
}
return res;
}