You are given an array nums with an even number of integers, 2n of them. Split them into n pairs so that every number is in exactly one pair.
Each pair scores the smaller of its two numbers. Return the largest total score you can get over all the pairs.
Example 1
Input: nums = [4, 1, 4, 2] Output: 5 Why: pairs (1, 2) and (4, 4) score 1 + 4
2 more examples and the constraints
Example 2
Input: nums = [4, 4, -2, 0, 6, -2] Output: 2 Why: pairs (-2, -2), (0, 4), (4, 6) score -2 + 0 + 4
Example 3
Input: nums = [5, 5] Output: 5 Why: only one pair is possible
Constraints
- 1 ≤ n ≤ 10,000, and nums has exactly 2n numbers
- −10,000 ≤ nums[i] ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort and pair neighboursO(n log n)
- Counting sortO(n + R)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20,000 numbers | Verdict |
|---|---|---|---|
| Sort and pair neighbours | O(n log n) | Short and clear; the usual answer | |
| Counting sort | O(n + R) | Best; uses the small value range |
n = length of nums, R = 20,001 possible values.
Edge cases to test
- Only one pair. [5, 5] or [-3, 8]: the answer is the smaller number.
- Negative numbers. They sort before the positives like any other value; in counting sort, shift them by 10,000 to get an index.
- Duplicates. Two equal numbers can pair with each other and lose nothing; counting must step through each copy, not each distinct value.
- Input order. Sorted, reversed or shuffled input all give the same answer; only the multiset of values matters.
Common mistakes
- Pairing the smallest with the largest, which throws away the big numbers.
- In counting sort, flipping
takeonce per distinct value instead of once per copy. - Forgetting the 10,000 offset, so negative values index outside the count array.
How to talk through it
- 1Clarify. Is the length always even? Can numbers be negative or repeat? Do I return the score or the pairs?
- 2Find the greedy rule. The smallest number always counts; its partner never does, so give it the second smallest.
- 3Sort and sum. Sort, then add the numbers at even indexes: O(n log n).
- 4Use the value range. Values lie in −10,000 to 10,000, so a counting sort gives O(n + R).
- 5Test out loud. Run [4, 1, 4, 2] and a case with negatives and duplicates.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?