Easy to Understand TC: O(n), SC: O(1); Tracking 2ndMin & 2ndMax


  • 0
    A
    public int maxDistance(int[][] a) {
            int min = Integer.MAX_VALUE, minnext = min;
            int max = Integer.MIN_VALUE, maxprev = max;
            int start = 0, end = 0;
            
            for(int i = 0; i<a.length; i++){
                if(a[i][0]<minnext){
                    minnext = a[i][0];
                    if(a[i][0] <= min) {
                        minnext = min;
                        min = a[i][0];
                        start = i;
                    }
                }
                if(a[i][a[i].length-1] > maxprev){
                    maxprev = a[i][a[i].length-1];
                    if(a[i][a[i].length-1] >= max){
                        maxprev = max;
                        max = a[i][a[i].length-1];
                        end = i;
                    }
                }
            }
            if(start!=end)
                return Math.abs(max-min);
            else
                return Math.max(Math.abs(maxprev-min), Math.abs(max-minnext));
        }

Log in to reply
 

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