Max Number of K-Sum Pairs - Problem
You have an integer array nums and a target value k. Your goal is to maximize the number of operations you can perform on the array.
In each operation, you can:
- Pick any two numbers from the array whose sum equals
k - Remove both numbers from the array
- Count this as one operation
Return the maximum number of operations you can perform until no more valid pairs exist.
Example: If nums = [1,2,3,4] and k = 5, you can pair (1,4) and (2,3) for a total of 2 operations.
Input & Output
example_1.py โ Basic case
$
Input:
nums = [1,2,3,4], k = 5
โบ
Output:
2
๐ก Note:
We can form pairs (1,4) and (2,3), both summing to 5. This gives us 2 operations total.
example_2.py โ Multiple duplicates
$
Input:
nums = [3,1,3,4,3], k = 6
โบ
Output:
1
๐ก Note:
Only one pair (3,3) can be formed that sums to 6. Even though there are three 3's, we can only use two of them for one operation.
example_3.py โ No valid pairs
$
Input:
nums = [1,1,1,1], k = 3
โบ
Output:
0
๐ก Note:
No two elements can sum to 3 since all elements are 1, and 1+1=2 โ 3.
Visualization
Tap to expand
Understanding the Visualization
1
Dancers Arrive
As each dancer arrives, we check our waiting list for their perfect height complement
2
Perfect Match Found
If the complement exists, we immediately pair them up and they start dancing
3
Join Waiting List
If no perfect partner is waiting, the dancer joins our waiting list
4
Maximize Pairs
This process ensures we form pairs as quickly as possible, maximizing the total number of dancing pairs
Key Takeaway
๐ฏ Key Insight: Instead of checking all possible pairs (O(nยฒ)), we use a hash table to instantly find perfect partners in O(1) time, achieving optimal O(n) performance.
Time & Space Complexity
Time Complexity
O(n)
Single pass through array with O(1) hash map operations
โ Linear Growth
Space Complexity
O(n)
Hash map can store up to n unique elements in worst case
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- 1 โค k โค 109
- Follow-up: Can you solve this in O(n) time?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code