1679. Max Number of K-Sum Pairs
Problem
In one operation, remove two numbers from nums whose sum is k. Return the maximum number of operations you can perform.
Example: nums = [1,2,3,4], k = 5 → 2; nums = [3,1,3,4,3], k = 6 → 1
Constraints: n ≤ 10⁵.
Two Sum, counted: scan once; if a waiting partner k − x exists, pair them (use it up); otherwise leave x waiting. (Sorting + opposite-end pointers also works in O(n log n).)
Complexity: O(n).
class Solution:
def maxOperations(self, nums: List[int], k: int) -> int:
waiting, ops = Counter(), 0
for x in nums:
if waiting[k - x]:
waiting[k - x] -= 1
ops += 1
else:
waiting[x] += 1
return ops
assert Solution().maxOperations([1, 2, 3, 4], 5) == 2
assert Solution().maxOperations([3, 1, 3, 4, 3], 6) == 1
assert Solution().maxOperations([2, 2, 2, 2], 4) == 2
assert Solution().maxOperations([1], 2) == 0
class Solution {
public int maxOperations(int[] nums, int k) {
Map<Integer, Integer> waiting = new HashMap<>();
int ops = 0;
for (int x : nums) {
int c = waiting.getOrDefault(k - x, 0);
if (c > 0) { waiting.put(k - x, c - 1); ops++; }
else waiting.merge(x, 1, Integer::sum);
}
return ops;
}
}
func maxOperations(nums []int, k int) int {
waiting, ops := map[int]int{}, 0
for _, x := range nums {
if waiting[k-x] > 0 { // pair x with an earlier k-x
waiting[k-x]--
ops++
} else {
waiting[x]++
}
}
return ops
}