The minimum total movement in the balance, if we can increase / decrease a specific element of the array by 1

This is code 462. I have one algorithm, but it did not pass some tests, passing to others. I tried to think it over, but I'm not sure what a corner case is that I forgot.

We have one array of N elements. One step is defined as increasing OR decreasing one element of the array by 1. We are trying to find the minimum number of moves to make all elements equal.

My idea: 1. Find the average 2. Find the element closest to the middle 3. summarize the difference between each element and the element closest to the average. What am I missing? Please provide one example.

class Solution {
public:
    int minMoves2(vector<int>& nums) {
        int sum=0;
        for(int i=0;i<nums.size();i++){
            sum += nums[i];
        }
        double avg = (double) sum / nums.size();
        int min = nums[0];
        int index =0 ;
        for(int i=0;i<nums.size();i++){
            if(abs(nums[i]-avg) <= abs(min - avg)){
                min = nums[i];
                index = i;
            }
        }
        sum=0;
        for(int i=0;i<nums.size();i++){
            sum += abs(min - nums[i]);
        }
        return sum;
    }
};
+4
source share
1 answer

, [1, 1, 10, 20, 100]. 20. , 19 + 19 + 10 + 0 + 80 = 128. , 10 ? 9 + 9 + 0 + 10 + 90 = 118. .

, T. , T? T, , T 1. T 1, , T, , , , . , T , , , T. , T . , T , ( , , T ).

+3
source

Source: https://habr.com/ru/post/1684718/


All Articles