Simple and Easy Understanding JAVA Solution


  • 17
    G
    public int maxArea(int[] height) {
        int maxA = 0;
        
        int i = 0, j = height.length-1;
        
        while(i < j) {
            int H = Math.min(height[i], height[j]);
            int W = j - i;
            maxA = Math.max(maxA, H*W);
            
            while(i < j && height[i] <= H) {
                ++i;
            }
            while(i < j && height[j] <= H) {
                --j;
            }
        }
        return maxA;
    }

  • 0
    R

    Awesome explanation :)


  • 0
    G

    Agreed, it's especially insightful that you attempt to move both indicies with each execution of the outer loop. Great answer!


  • 0
    L

    Two while loops, can this solution be O(n^2)?


  • 0
    U

    No, because when the two pointers meet each other, then it stops.
    So, absolutely O(n).


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.