Alternate O(N log N) solution (equivalent to the min-subtract approach)


  • 0
    P
    class Solution {
    public:
        int minMoves(vector<int>& nums) {
            if (nums.size() <= 1)
                return 0;
            sort(nums.begin(), nums.end(), greater<int>());
            int sum = 0;
            int factor = 1;
            for (int i = 0; i < nums.size() - 1; ++i, ++factor){
                sum += factor * (nums[i] - nums[i + 1]);
            }
            return sum;
        }
    };
    
    

Log in to reply
 

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