【LeettCode】14.Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). 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.

最基础的方法 O(n2),会超时,跟最大直方图略像,但是不一样,最大直方图是至少包括一个完整的柱子,本题是有两个line决定一个面积。

 

public class Solution {
    public int maxArea(int[] height) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
            
	         Stack<Integer> stack = new Stack<Integer>();
        int i = 0;
        int j = height.length-1;
        int maxArea = 0;
        while(i < j){
            if(height[i]<height[j]){
                maxArea = Math.max(maxArea,height[i]*(j-i));
                i++;
            }else if(height[i]>height[j]){
                maxArea = Math.max(maxArea,height[j]*(j-i));
                j--;
            }else{
                maxArea = Math.max(maxArea,height[i]*(j-i));
                i++;
                j--;
            }
        }
        return maxArea;
    }
}

  

posted @ 2013-10-26 16:11  果汁果粒  阅读(224)  评论(0编辑  收藏  举报