Java Two-Pointer Solution with Inline Comment


  • 0
    A

    Mission is to maximize container size, to do that, you need to look for the furthest taller edge this [i] edge can reach. Note, an edge slightly taller but further, is better than a huge edge very close by, since the max height limited by itself [i], not the taller edge's height!

        public int maxArea(int[] height) {
            int container = 0;
    
            // the shorter edge meets taller, guarantees is the furthest taller edge it can meet
            // two pointer from two ends
            for (int a = 0, b = height.length-1; a < b; ) {
                int heightA = height[a];
                int heightB = height[b];
                
                int curr = (b - a) * Math.min(heightA, heightB);
                container = Math.max(container, curr);
                
                // if eqls, increase both pointers
                if (heightA <= heightB) a++;
                if (heightA >= heightB) b--;
            }
            return container;
        }
    

Log in to reply
 

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