2ms, Java, beat 99.86%


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

  • 0
    X

    I found our solutions quite similar. Sharing mine which might be a little bit cleaner and clearer.

    public class Solution {
        public int maxArea(int[] height) {
            int p=0, q=height.length-1;
            int max=0, h=0;
            while(p<q){
                h = Math.min(height[p],height[q]);
                max = Math.max(max, h*(q-p));
                
                while(p<height.length && h>=height[p])    p++;
                while(q>=0 && h>=height[q])  q--;
            }
            return max;
        }
    }
    

Log in to reply
 

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