Share My O(n) solution


  • 9
    X
    public int maxDistance(int[][] arrays) {
    		if (arrays == null || arrays.length == 0) return 0;
    		
    		int diff = Integer.MIN_VALUE;
    		int m = arrays.length;
    		
    		int min =  arrays[0][0], max = arrays[0][arrays[0].length-1];
    		for (int i = 1; i < m; i++) {
    			int head = arrays[i][0];
    			int tail = arrays[i][arrays[i].length-1];
    			diff = Math.max(Math.abs(max-head), diff);
                            diff = Math.max(Math.abs(tail-min), diff);
    			max = Math.max(tail, max);
    			min = Math.min(head, min);
    		}
    		
    		return diff;
        }
    

  • 0

    nice solution, thanks!

    	if (Math.abs(max-head) > diff) {
    	  diff = Math.abs(max-head);
    	}
    	if (Math.abs(tail-min) > diff) {
    	  diff = Math.abs(tail-min);
    	}
    

    could be reduced to

    diff = Math.max(Math.abs(max-head), diff);
    diff = Math.max(Math.abs(tail-min), diff);
    

Log in to reply
 

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