Posted on

Description

Submission

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int n = nums.size();
        long long ret = 0;

        for(int x: nums) {
            ret += (x - nums[0]);
        }

        for(int i = 1; i < n; ++i) {
            ret = min(ret, ret + (nums[i] - nums[i-1]) * (2 * i - n));
        }

        return ret;
    }
};


// 1 2 9 10

// 1 + 8 + 9


// (nums[i] - nums[i-1]) * (i + 1 - (n - i + 1))
//                         (2 * i - n)

Leave a Reply

Your email address will not be published. Required fields are marked *