Problem Description
Given an integer array nums, find the maximum sum of a pair of numbers such that the largest digit (when considering each number's digits) in both numbers is the same. If no such pair exists, return -1.
Key Insights
- The largest digit for a number can be derived by examining all its digits.
- Group the numbers by their largest digit.
- For each group, maintain the top two largest numbers to compute the potential maximum pair sum.
- If a group has fewer than two numbers, ignore that group.
- Finally, choose the maximum sum among all valid groups.
Space and Time Complexity
Time Complexity: O(n * d) where n is the number of elements and d is the number of digits per number (constant-time operation given the input constraints). Space Complexity: O(n), to store the grouping of numbers based on their largest digit.
Solution
The solution involves the following steps:
- Iterate through each number in the array.
- For each number, determine the largest digit by converting the number to a string and checking each digit.
- Group numbers by this largest digit. For each group, keep track of the top two largest numbers.
- Iterate over the groups and calculate the sum of the top two numbers for each group (if available).
- Return the maximum sum found or -1 if no valid pair exists.
The main data structure used is a hash table (or dictionary) to map each largest digit to a pair of its highest numbers. This approach simplifies grouping and efficient pair selection while ensuring we meet the problem constraints.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java with line-by-line comments.