题目:
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.
题解:这题目大概是说在x轴的垂直方向上(即y轴)有一条一条的线,它们以(i,0)开始到(i,ai)结束,挑两个线组成一个最大面积的容器可以装下更多的水。
这里面有一个短板的问题,对于任意两条线ia,ib我们可以得出一个公式S = Math.abs((ia-ib))*Math.min(height[ia],height[ib]).这道题当然我们可以用遍历的方法解决,最简单的遍历时间复杂度应该是O(n^2)很明显这不符合我们的预期。
首先我们要明确一个性质:如果一个容器能有比他更大的容器,突破点一定在高的那个柱子上。
就好像图中的a1区域,要想找到比a1区域更大的区域,肯定最大值在左侧更高的那个柱子上。并且有且只有这一个最大值。
现在我们来严格的证明一下这个性质:
对于1和8来说他们中间相隔的宽度为7,高度8要低一点,假设高为h8,容器面积为s18,那么如果我们不从1找突破点而从8开始的话,如果新的i(1<i<8)的高hi<h8
它的si8 = hi*(8-i)很明显小于s18,反过来如果hi>h8的话si8 = h8*(8-i)一样的很明显小于s18,所以如果有一个面积大于s18,它的一端一定在1上。
public int maxArea(int[] height){
int left=0;
int right=height.length-1;
int max=0;
while(left<right){
int area=(right-left)*Math.min(height[left], height[right]);
max=Math.max(max, area);
if(height[left]>height[right])
right--;
else
left++;
}
return max;
}