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.
解题思路:
本题是经典的“水箱”问题,最简单的方法是暴力枚举,时间复杂度是O(N^2),当然无法通过。
本题有三个特征:
一、水箱的高度是由最短那根木板决定的
二、最终符合条件的两根木板肯定比他们各自外围的木板长
三、最终符合条件的两个木板的外围高度要小于这两个木板中最短的那个,即最终符合条件的两个木板肯定是所有遍历过的最高的两个(比较拗口,但是是解决本题的关键)
因此我们可以从最外围木板出发,向内遍历,每次替换掉两个之中最短的木板,肯定能遍历到最大容器(目标木板)。
JAVA实现如下:
static public int maxArea(int[] height) {
if (height.length < 2)
return 0;
int maxV = 0, start = 0, end = height.length - 1;
while (start < end) {
int area = Math.min(height[start], height[end]) * (end - start);
maxV = Math.max(maxV, area);
if (height[start] > height[end])
end--;
else
start++;
}
return maxV;
}
C++:
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
if (height.size() < )
return ;
int maxV = , start = , end = height.size() - ;
while (start < end) {
maxV = max(maxV, min(height[start], height[end]) * (end - start));
if (height[start] > height[end])
end--;
else
start++;
}
return maxV;
}
};