Skip to content

1679. Max Number of K-Sum Pairs 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maxOperations(vector<int>& nums, int k) {
    int ans = 0;
    unordered_map<int, int> count;

    for (const int num : nums)
      ++count[num];

    for (const auto& [num, freq] : count)
      if (const auto it = count.find(k - num); it != count.end())
        ans += min(freq, it->second);

    return ans / 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int maxOperations(int[] nums, int k) {
    int ans = 0;
    HashMap<Integer, Integer> count = new HashMap<>();

    for (final int num : nums)
      count.merge(num, 1, Integer::sum);

    for (final int num : count.keySet()) {
      final int complement = k - num;
      if (count.containsKey(complement))
        ans += Math.min(count.get(num), count.get(complement));
    }

    return ans / 2;
  }
}
1
2
3
4
5
class Solution:
  def maxOperations(self, nums: list[int], k: int) -> int:
    count = collections.Counter(nums)
    return sum(min(count[num], count[k - num])
               for num in count) // 2