When you break your head for recursion cause it's cool and a simple for loop solves it instead.


  • 0
    B

    The first attempt at solving this question was obviously using recursion, cause you know, it's awesome and you feel good about yourself.
    But for some reason, it exceeded the time limit.

            Arrays.sort(nums);
            int diffMax = nums[nums.length-1]-nums[0];
            if(nums[0]==nums[nums.length-1]) 
                return 0;
            else {
                for(int i=0;i<nums.length-1;i++) {
                    nums[i] = nums[i]+diffMax;
                }
                return diffMax+minMoves(nums);
            }
    }
    
    Now, the easier solution uses a simple for loop.
    
           Arrays.sort(nums);
            int sum = 0;
            int firstVal = nums[0];
            for(int elem:nums) {
                sum+=elem-firstVal;
            }
            return sum;

Log in to reply
 

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