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.
Java代码实现
//设置left、right两个下标,代表左右两条直线,从两端开始遍历,对于两条直线和X轴所形成的的容器,若左边的直线高度大于右边的直线高度,则右边直线下标right--,反之左边下标直线下标left++。
//因为容器所成盛水的体积等于宽度(right-left)乘以较低的直线高度,淘汰较低的直线高度,尝试寻找更高的直线高度,继而尝试寻找更大的体积。
public class Solution {
public int maxArea(int[] height) {
if(height == null || height.length == 0)
return 0;
int left = 0;
int right = height.length - 1;
int max_area = 0;
int area = 0;
while(left < right){
if(height[left] > height[right]){
area = height[right] * (right - left);
right--;
}
else{
area = height[left] * (right - left);
left++;
}
if(area > max_area){
max_area = area;
}
}
return max_area;
}
}