[LeetCode] 11. Water filled up container (double pointer)

topic

Given n non-negative integers a1, a2, ..., an, a point (i, ai) each represents the number of coordinates. Videos n lines in vertical coordinate, i is a vertical line two end points are (i, AI) and (i, 0). Find out the two lines, which together with the container so that the x-axis configuration can accommodate up water.

answer

Double pointer, each of the short side inside shift (because of the high area = low height, length and now is the longest, so in this case the maximum area is made shorter boundary), and maintains the maximum area.

Code

class Solution {
    public int maxArea(int[] height) {
        if(height==null||height.length<2){
            return 0;
        }
        
        int maxArea=0;
        int l=0;
        int r=height.length-1;
        while(l<r){
            int area=Math.min(height[l],height[r])*(r-l);
            maxArea=area>maxArea?area:maxArea;
            if(height[l]<height[r]){
                ++l;
            }
            else{
                --r;
            }
        }
        return maxArea;
    }
}

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11279425.html