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.
第一反应是2个循环遍历向量,时间复杂度为O(n^2),超时。
优化方法:两边向中间逼近,因为水量取决于矮的那个板,所以再移动高的那个没有意义,只要移动矮的就行。
int maxArea(vector<int> &height)
{
int left = 0, right = height.size()-1;
int maxRes = 0;
while(left < right)
{
int minHeight = min(height[left],height[right]);
int temp = minHeight*(right-left);
maxRes = maxRes > temp ? maxRes : temp;
height[left] > height[right] ? right-- : left++;
}
return maxRes;
}