Java simple solution with example (math solution)


  • 0
    B
     public int minMoves(int[] nums) {
            int steps = 0;
            Arrays.sort(nums);
            for(int i = 1; i < nums.length; i++) {
                steps = steps + nums[i] - nums[0];
            }
            return steps;
        }
    
    

    Assume the input is [1,3,5,7], the left one is following the questions's guide, the right one is subtracting the maximum value in the array by 1. Base on the right one, we can see that the steps equals to sum of the subtraction of [all the numbers except the minimum one] and [the minimum one].
    [1,3,5,7] [1,3,5,7]
    [2,4,6,7] [1,3,5,6]
    [3,5,7,7] [1,3,5,5]
    [4,6,7,8] [1,3,4,5]
    [5,7,8,8] [1,3,4,4]
    [6,8,8,9] [1,3,3,4]
    [7,9,9,9] [1,3,3,3]
    [8,9,10,10] [1,2,3,3]
    [9,10,10,11] [1,2,2,3]
    [10,11,11,11] [1,2,2,2]
    [11,11,12,12] [1,1,2,2]
    [12,12,12,13] [1,1,1,2]
    [13,13,13,13] [1,1,1,1]


Log in to reply
 

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