题目
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.
题意解析:
a[i]:以索引i为x轴坐标,a[i]为y坐标,得到一个x-y轴的点。点到x轴的距离设置为容器的高,两点之间的x轴距离设为宽。求两点,使得三条线(两个索引的距离线,两条高)围成的容器装水最多。由于短板效应,所以计算公式为:索引距离*min(height1, height2)。
思路:
从最大宽度开始,①从高较短的点为向里收缩移动。如果这一次移动到的点的高大于上一个位置的点的高,则计算面积,若面积大于已知的最大值,则找到新的两个点。重复①操作,直至两个点会合。
AC代码
public int maxArea(int[] height){
int right = height.length - 1;
int left = 0;
int maxArea = 0;
while(left < right){
//左边为比较短
if(height[left] < height[right]){
int tmp = (right - left) * height[left];//计算当前容器的容积
if(tmp > maxArea){ //是否大于已知最大值
maxArea = tmp;
}
++left; //向中间收缩,以得到新的容器
}
//右边为比较短,操作和上面同理
else{
int tmp = (right - left) * height[right];
if(tmp > maxArea){
maxArea = tmp;
}
--right;
}
}
return maxArea;
}