Java solution using two pass


  • 0
    C
    public int minDistance(int height, int width, int[] tree, int[] squirrel, int[][] nuts) {
            int totalDistance = 0;
            
            for(int[] nut : nuts){
                totalDistance += (2 * absoluteDistance(nut, tree));
            }
            
            int minDistance = Integer.MAX_VALUE;
            for(int[] nut : nuts){
                minDistance = Math.min(minDistance, totalDistance - absoluteDistance(nut, tree) + absoluteDistance(nut, squirrel));
            }
            
            return minDistance;
        }
        
        private int absoluteDistance(int[] nut, int[] tree){
            return Math.abs(nut[0] - tree[0]) + Math.abs(nut[1] - tree[1]);
        }
    

Log in to reply
 

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