leetcode 11 最大盛水容器

原题

暴力法:

    public static int maxArea(int[] height) {
        int n = height.length;
        int ans = 0;

        for(int i=0;i<n-1;i++){
            for(int j=i+1;j<n;j++)
            {
                int len = j-i;
                int hei = Math.min(height[i],height[j]);
                ans = Math.max(ans,len*hei);
            }
        }
        return ans;
    }

贪心算法:

public static int maxArea2(int[] height) {
        int n = height.length;
        int ans = 0;
        int l=0,r=n-1;
        while(l<r){
            int hei = Math.min(height[l],height[r]);
            int wid = r-l;
            ans = Math.max(ans,hei*wid);
            if(height[l]>height[r]) r--;
            else l++;
        }
        return ans;
    }

猜你喜欢

转载自www.cnblogs.com/superxuezhazha/p/12600623.html
今日推荐