From 2b767f9fb3adfe9cc29327221ad41ba4ae6bcf6b Mon Sep 17 00:00:00 2001 From: eat-swap Date: Wed, 4 May 2022 19:07:46 +0800 Subject: [PATCH] add: 220504 [cpp] --- cpp/2205/220504.cpp | 28 ++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220504.cpp diff --git a/cpp/2205/220504.cpp b/cpp/2205/220504.cpp new file mode 100644 index 0000000..9336ce6 --- /dev/null +++ b/cpp/2205/220504.cpp @@ -0,0 +1,28 @@ +#include +#include + +/** + * 1679. Max Number of K-Sum Pairs + * You are given an integer array nums and an integer k. + * In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array. + * Return the maximum number of operations you can perform on the array. + */ + +class Solution { +public: + static int maxOperations(const std::vector& nums, int k) { + std::unordered_map m; + for (int i : nums) + ++m[i]; + int ret = (k & 1) ? 0 : (m[k / 2] / 2); + const int pivot = (k & 1) ? (k / 2 + 1) : (k / 2); + for (const auto& [idx, cnt] : m) + if (idx < pivot && m.count(k - idx)) + ret += std::min(m[idx], m[k - idx]); + return ret; + } +}; + +int main() { + Solution::maxOperations({2,2,2,3,1,1,4,1}, 4); +} diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index 991851c..913d619 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220504-CN.cpp) +ADD_EXECUTABLE(2204 220504.cpp)