leetcode-11 Container With Most Water

 

/**
 * 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.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

leetcode-11 Container With Most Water

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49
 *
 */
public class ContainerWithMostWater {

    /**
     * 由题意可知 即求出两个y坐标与x坐标围绕的最大面积(x之间的距离*y上的第二个最大值)    
     * @param height
     * @return
     */
    public int maxArea(int[] height) {
        int max = 0;
        if(height == null || height.length <=1) {
            return max;
        }else {
            for(int i=0;i<height.length-1;i++) {
                int tmpMax = height[i];
                int tmpHeight = tmpMax;
                for(int j=i+1;j<height.length;j++) { 
                    tmpHeight = tmpMax>=height[j]? height[j]:tmpMax;
                    max = max > (j-i)*tmpHeight? max:(j-i)*tmpHeight;
                }
            }
        }
        
        return max;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ContainerWithMostWater a = new ContainerWithMostWater();
        int[] as = new int[] {1,8,6,2,5,4,8,3,7};
        System.out.println(a.maxArea(as));
    }

}
 

以上为最麻烦的 暴力的遍历

可以调用方法从两端开始 i=0  j=height.length()-1

计算出当前的值 然后根据height[i]与height[j]的大小比较 来判断是i++或是j--

知道i<j不成立