[LeetCode] Max Number of K-Sum Pairs

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int maxOperations(vector<int>& A, int n) {
int res = 0;
unordered_map<int,int> mp;
for(auto& a : A) mp[a]++;
for(auto& [k, v] : mp) {
if(n - k == k) {
res += v / 2;
v -= v / 2;
} else if(mp.count(n-k)) {
int mi = min(v, mp[n - k]);
res += mi;
mp[n-k] -= mi;
v -= mi;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/04/PS/LeetCode/max-number-of-k-sum-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.