EASY UNDERSTAND SOLUTION(java,o(n))


  • 0
    M

    consider this:

    a[]={1,x,10}(1<=x<=10)
    to make 1 equal to 10, 9 steps needed
    {1,x,10}->{10,x+9,10}
    to make x+2 equal to 10, |x+9-10| steps needed
    the sum is x-1+10-1
    guess and verify:the result is the sum of the difference between element in the array and the min of the array

    so the method is

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

    but we only care the min number instead of order of the arrays,so the final code is :

    public class Solution {
        public int minMoves(int[] nums) {
            int ret=0;
            int min=nums[0];
            for(int i:nums){
                ret+=i;
                min=i<min?i:min;
            }
            return ret-min*nums.length;
        }
    }
    

Log in to reply
 

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