Simple Java O(NlogN) Solution Using Recursion


  • 0

    Below is my solution with O(NlogN) time complexity. Hope this could be helpful.

    public class Solution {
        public int minMoves(int[] nums) {
            if(nums.length <= 1) return 0;
            Arrays.sort(nums);
            return helper(nums, 1, nums[0]);
        }
        
        public int helper(int[] nums, int i, int min){
            return (i >= nums.length) ? 0 : nums[i]-min+helper(nums, ++i, min);
        }
    }
    

    Hint: Find out the sum of difference between each number and minimum number.

    PS: Thanks for rectification from butzhang.


  • 0
    B

    interesting solution but the time complexity should be O(nlogn)


  • 0

    Thank you for the rectification.


Log in to reply
 

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