Skip to content

Latest commit

 

History

History
69 lines (55 loc) · 2.08 KB

11. Container With Most Water.md

File metadata and controls

69 lines (55 loc) · 2.08 KB

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.

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

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

Solution

  • java

    • mine Runtime: 2 ms, faster than 95.41%, Memory Usage: 40 MB, less than 94.23% of Java online submissions
    //O(n)time O(1)space
    public int maxArea(int[] height) {
        int s = 1,e = height.length;
        int res = 0;
        int maxS = height[s - 1],maxE = height[e - 1];
        int maxSIndex = s,maxEIndex = e;
        while(s < e){
            res = Math.max(res, (maxEIndex - maxSIndex) * Math.min(maxS,maxE));
            if(maxS <= maxE){
                s++;
                if(height[s - 1] > maxS){
                    maxSIndex = s;
                    maxS = height[s - 1];
                }
            }else{
                e--;
                if(height[e - 1] > maxE){
                    maxEIndex = e;
                    maxE = height[e - 1];
                }
            }
        }
        return res;
    }
    
    • the most votes Runtime: 2 ms, faster than 95.41%, Memory Usage: 39.2 MB, less than 98.72% of Java online submissions
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1;
        int maxArea = 0;
    
        while (left < right) {
            maxArea = Math.max(maxArea, Math.min(height[left], height[right])
                    * (right - left));
            if (height[left] < height[right])
                left++;
            else
                right--;
        }
    
        return maxArea;
    }