From 5ff73e9efa0bd145b70a8361c0c67aeb5fd4cddd Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Fri, 1 Jul 2022 02:01:22 +0800 Subject: [PATCH] add: 220630 --- cpp/2206/220630.cpp | 27 +++++++++++++++++++++++++++ cpp/2206/CMakeLists.txt | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 cpp/2206/220630.cpp diff --git a/cpp/2206/220630.cpp b/cpp/2206/220630.cpp new file mode 100644 index 0000000..e3c02d0 --- /dev/null +++ b/cpp/2206/220630.cpp @@ -0,0 +1,27 @@ +#include +#include +#include + +/** + * 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& 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; + } +}; diff --git a/cpp/2206/CMakeLists.txt b/cpp/2206/CMakeLists.txt index 573f5c8..5e80c0a 100644 --- a/cpp/2206/CMakeLists.txt +++ b/cpp/2206/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2206) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2206 220629.cpp) +ADD_EXECUTABLE(2206 220630.cpp)