2815. Max Pair Sum in an Array
Description
You are given an integer array nums. You have to find the maximum sum of a pair of numbers from nums such that the largest digit in both numbers is equal.
For example, 2373 is made up of three distinct digits: 2, 3, and 7, where 7 is the largest among them.
Return the maximum sum or -1 if no such pair exists.
Example 1:
Input: nums = [112,131,411]
Output: -1
Explanation:
Each numbers largest digit in order is [2,3,4].
Example 2:
Input: nums = [2536,1613,3366,162]
Output: 5902
Explanation:
All the numbers have 6 as their largest digit, so the answer is 2536 + 3366 = 5902.
Example 3:
Input: nums = [51,71,17,24,42]
Output: 88
Explanation:
Each number's largest digit in order is [5,7,7,4,4].
So we have only two possible pairs, 71 + 17 = 88 and 24 + 42 = 66.
Constraints:
2 <= nums.length <= 1001 <= nums[i] <= 104
Solutions
Solution 1: Enumeration
Thinking
With \(n\le 100\), every pair can be enumerated and accepted when the two numbers share the same maximum decimal digit. Grouping by that digit is unnecessary under this constraint.
First, we initialize the answer variable \(ans=-1\). Next, we directly enumerate all pairs \((nums[i], nums[j])\) where \(i \lt j\), and calculate their sum \(v=nums[i] + nums[j]\). If \(v\) is greater than \(ans\) and the largest digit of \(nums[i]\) and \(nums[j]\) are the same, then we update \(ans\) with \(v\).
The time complexity is \(O(n^2 \times \log M)\), where \(n\) is the length of the array and \(M\) is the maximum value in the array.
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |