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; } };
, [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 ).
Source: https://habr.com/ru/post/1684718/More articles:pandas: create columns with the same size and sum after a group across multiple columns - pythonHttpClient StreamContent appends file name twice - content-typePOST StreamContent с несколькими файлами - jsonWhat is the purpose of using double underscore (__) before and after the filename in c? - cAnaconda will install Tensorflow missing "audio_ops" from Contrib framework - tensorflowSwimlane ngx-charts in Angular2 - Different colors on one line chart - javascriptUITextView boundingRect не работает должным образом - iosWhy has my directory search been taking so long? - c #Kotlin & Spring Boot @ConfigurationProperties - springCould not detect actual page reload - javascriptAll Articles