#2815
Max Pair Sum in an Array
EasyArrayHash TableHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
We can optimize the solution by using a hash map to group numbers by their largest digit. This allows us to find pairs efficiently without checking every combination.
⚙️
Algorithm
4 steps- 1Step 1: Create a hash map where the key is the largest digit and the value is a list of numbers that have that largest digit.
- 2Step 2: Iterate through the array and populate the hash map.
- 3Step 3: For each entry in the hash map, if there are at least two numbers, calculate the sum of the two largest numbers and update the maximum sum.
- 4Step 4: Return the maximum sum found or -1 if no valid pairs exist.
solution.py18 lines
1# Full working Python code
2
3def maxPairSum(nums):
4 from collections import defaultdict
5
6 def largest_digit(num):
7 return max(int(d) for d in str(num))
8
9 digit_map = defaultdict(list)
10 for num in nums:
11 digit_map[largest_digit(num)].append(num)
12
13 max_sum = -1
14 for numbers in digit_map.values():
15 if len(numbers) > 1:
16 numbers.sort(reverse=True)
17 max_sum = max(max_sum, numbers[0] + numbers[1])
18 return max_sumℹ
Complexity note: The time complexity is O(n log n) due to sorting the lists of numbers in the hash map. The space complexity is O(n) because we store all numbers in the hash map.
- 1Using a hash map can significantly reduce the number of comparisons needed.
- 2Sorting the groups allows us to easily find the two largest numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.