Max Number of K-Sum Pairs LeetCode solution in C++

1
class Solution {
2
public:
3
int maxOperations(vector<int> &nums, int k) {
4
unordered_map<int, int> Map;
5
for (auto &num : nums) Map[num]++; // count freq of nums
6
int ans = 0;
7

8
for (auto it = Map.begin(); it != Map.end(); ++it) {
9
int num = it->first, count = it->second;
10
if (k - num == num)
11
ans += count / 2; // if num is half of k add half of it's count in ans
12
else if (Map.count(k - num)) { // find k-num in nums and add min freq of
13
// num or k-num to ans
14
int Min = min(count, Map[k - num]);
15
ans += Min;
16
Map[num] -= Min;
17
Map[k - num] -= Min;
18
}
19
}
20

21
return ans;
22
}
23
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0