add: 220630

This commit is contained in:
Eat-Swap 2022-07-01 02:01:22 +08:00
parent e316b450e6
commit 5ff73e9efa
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 28 additions and 1 deletions

27
cpp/2206/220630.cpp Normal file
View File

@ -0,0 +1,27 @@
#include <vector>
#include <numeric>
#include <algorithm>
/**
* 462. Minimum Moves to Equal Array Elements II
* Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
* In one move, you can increment or decrement an element of the array by 1.
* Test cases are designed so that the answer will fit in a 32-bit integer.
*/
class Solution {
public:
static int minMoves2(std::vector<int>& nums) {
int psum = 0, ssum = std::accumulate(nums.begin(), nums.end(), 0);
long long ans = 0x7FFFFFFF;
const int n = nums.size();
std::sort(nums.begin(), nums.end());
for (int i = 0; i < n; ++i) {
const long long t = nums[i];
ssum -= t;
ans = std::min(ans, t * (i - n + i + 1) + ssum - psum);
psum += t;
}
return ans;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2206)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2206 220629.cpp) ADD_EXECUTABLE(2206 220630.cpp)