Max Number of K-Sum Pairs - 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4], k = 5
Output: 2
💡 Note: We can form pairs (1,4) and (2,3), both sum to 5. Total operations: 2.
Example 2 — Duplicates
$ Input: nums = [3,1,3,4,3], k = 6
Output: 1
💡 Note: We can form one pair (3,3) that sums to 6. The remaining elements [1,4,3] cannot form valid pairs.
Example 3 — No Valid Pairs
$ Input: nums = [1,1,1,1], k = 3
Output: 0
💡 Note: No two elements sum to 3 (1+1=2), so no operations possible.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ 109
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Max K-Sum Pairs: Find and Remove PairsInput Array:1234k = 5Find Pairs That Sum to k:Pair 1: (1, 4) → 1 + 4 = 5 ✓Pair 2: (2, 3) → 2 + 3 = 5 ✓After Removal:EmptyEmptyEmptyEmptyMaximum Operations: 2
Understanding the Visualization
1
Input
Array of numbers and target sum k
2
Process
Find pairs that sum to k and remove them
3
Output
Maximum number of operations (pairs removed)
Key Takeaway
🎯 Key Insight: Each number can only be used once, so we need to efficiently count available numbers and match them with their complements.
Asked in
Amazon 42 Facebook 38 Google 31 Microsoft 25
89.4K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen