11. Container With Most Water - Medium

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 (iai) 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.

 

Example:

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

 

two pointers

p1, p2分别从首、尾开始扫描数组,同时计算面积。长方形面积中的底是一直在减小的(每次减少1),高是两条边中较短的边长,如果当前p1对应的边长小于p2对应的边长,应该保留较长的边(即p2),p2不变,p1向右移动,面积增大的可能性更大(理由:如果保留p1而移动p2,如果p2移动后变大,边长还是取较短的p1,如果p2移动后变小,边长取这个较小的新边长。新的边长 <= p1,即,移动后边长不会增加;但是如果保留p2而移动p1的话,如果p1移动后变大,边长可以取新的较大的边长或p2,即,移动后边长有增加的可能)。反之则应该移动p2。

时间:O(N),空间:O(1)

class Solution {
    public int maxArea(int[] height) {
        int p1 = 0, p2 = height.length - 1;
        int max = 0;
        while(p1 < p2) {
            int area = (p2 - p1) * Math.min(height[p1], height[p2]);
            max = Math.max(max, area);
            if(height[p1] < height[p2])
                p1++;
            else
                p2--;
        }
        return max;
    }
}

 

posted @ 2018-12-04 02:57  fatttcat  阅读(105)  评论(0编辑  收藏  举报