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.spa

給定n個非負整數a1,a2,...,an,其中每一個表明座標(i,ai)處的一個點。 繪製n條垂直線,使得線i的兩個端點處於(i,ai)和(i,0)處。 找到兩條線,它們與x軸一塊兒造成一個容器,以使容器包含最多的水。
注意:您不得傾斜容器。指針

 

/*
     * 貪心算法:從兩邊開始向中間縮小;每一步比較左右邊界高度,高度小的那個向裏走一步
     * 
     * 這個貪心算法,爲何最優解不會被錯過?         反證法 假設會被錯過。
     *         假設最優解是橫座標爲x1,x2(x2在右邊)的這兩個點組成的
     *               只考慮掃描到x2時,x1被錯過的狀況(x2被錯過同理):
     *         被錯過指的是 當右指針向左掃描通過x2以後,左指針還在x1的左邊P處時,x1被錯過。
     * 
     *                     狀況一   x2>p:  x2會被保留,而後左指針向右移動到x1,x1不會被錯過
     *                     狀況二   x2<p:  小狀況一:height[p]>height[x1]    則最優解爲 p,x2而不是 x1,x2。  假設不成立
     *                                   小狀況二:p<=x1  最優解仍是p,x2。 假設不成立
     *                             //由於x2比p和x1都小,因此容器高度取決於x2,而p比x1偏左,因此p,x2比x1,x2面積大
     *                         
     *        
     */
    public int maxArea(int[] height) {
        if(height.length<=2) return 0;
        
        int left=0,right=height.length-1;
        int maxArea=0;
        while(left<right) {
            int area = Math.min(height[left],height[right])*(right-left);
            maxArea = Math.max(maxArea, area);
            if(height[left]<=height[right]) {
                left++;
            }else {
                right--;
            }
        }
        return maxArea;
    }
相關文章
相關標籤/搜索