SDE & MLE Prep

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