Leetcode 11) Contain With Most Water

image

My solution

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

Other Answer

class Solution {
    public int maxArea(int[] height) {
        // maximize (j-i)*min(height[i], height[j])
        int n = height.length;
        int i = 0;
        int j = n-1;
        int maxArea = 0;
        while(i<j){
            int area = 0;
            if(height[i] < height[j]){
                int iHeight = height[i];
                area = (j-i)*iHeight;
                while(height[++i] < iHeight);
            } else {
                int jHeight = height[j];
                area = (j-i)* jHeight;
                while(height[--j] < jHeight);
            }
            maxArea = Math.max(maxArea, area);
        }
        return maxArea;
    }
}

/*
        int n = height.length;
        int maxArea = 0;
        for(int i = 0; i < n-1; i++){
            for(int j = i+1; j < n; j++){
                int area = (j-i)* Math.min(height[i], height[j]);
                maxArea = Math.max(maxArea, area);
            }
        }
        return maxArea;
*/

© 2018. All rights reserved.

Powered by Hydejack v8.5.2