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.
在二维坐标系中,(i, ai) 表示 从 (i, 0) 到 (i, ai) 的一条线段,任意两条这样的线段和 x 轴组成一个木桶,找出能够盛水最多的木桶,返回其容积(这里只算面积)
网上比较好的解题思路
由于桶是以最小高度和底边长的直径,例如:当左边小于右边高度时,面积都是以左边高度算面积,此时底边直径最大,左边与当前右边的其他情况不考虑,所以直接记录面积将左边右移。
/**O(n) * Created by a819 on 2017/8/7. */ public class Solution { public int maxArea(int[] height){ int i=0,j=height.length-1; int area=0,max=0; if(height.length<2) return 0; while(i<j){ if (height[i] >=height[j]) { area=height[j]*(j-i); if (area>max) max=area; j--; } else{ area=height[i]*(j-i); if (area>max) max=area; i++; } } return max; } }