add: 220504 [cpp]

This commit is contained in:
eat-swap 2022-05-04 19:07:46 +08:00
parent 7f11d372ef
commit 2b767f9fb3
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 29 additions and 1 deletions

28
cpp/2205/220504.cpp Normal file
View File

@ -0,0 +1,28 @@
#include <vector>
#include <unordered_map>
/**
* 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<int>& nums, int k) {
std::unordered_map<int, int> 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);
}

View File

@ -3,4 +3,4 @@ PROJECT(2205)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2204 220504-CN.cpp)
ADD_EXECUTABLE(2204 220504.cpp)