AAlgoLoopSpaced repetition for LeetCode
MEDIUMHash Map / SetLeetCode ↗

Max Number of K-Sum Pairs

The key idea

Each number x can only ever pair with its complement k - x. Count how many of each value you have, then each removed pair consumes one x and one (k - x). With a frequency map you settle every value in a single pass; for value x you can form min(count[x], count[k-x]) pairs, and self-pairs (when 2x = k) use count[x] // 2.

Problem

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.

Constraints

Examples

Input: nums=[1,2,3,4], k=5 Output: 2
Input: nums=[3,1,3,4,3], k=6 Output: 1

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Hash Map / Set problems