Using list- TC: O(n), SC: O(1); Tracking 2ndMin & 2ndMax


  • 0
    A
    public int maxDistance(List<List<Integer>> a) {
            int min = Integer.MAX_VALUE, minnext = min;
            int max = Integer.MIN_VALUE, maxprev = max;
            int start = 0, end = 0, i = 0;
            
            for(List<Integer> l: a){
                i++;
                if(l.get(0)<minnext){
                    minnext = l.get(0);
                    if(l.get(0) <= min) {
                        minnext = min;
                        min = l.get(0);
                        start = i;
                    }
                }
                if(l.get(l.size()-1) > maxprev){
                    maxprev = l.get(l.size()-1);
                    if(l.get(l.size()-1) >= max){
                        maxprev = max;
                        max = l.get(l.size()-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.