Problem Description
Given an array of positive integers, find two different elements such that the sum of their digits is equal and their combined value is maximized. If no such pair exists, return -1.
Key Insights
- Calculate the digit sum for each number.
- Use a hash table (dictionary) to group numbers by their digit sum.
- Keep track of the maximum number encountered so far for each digit sum.
- For each number, if a number with the same digit sum has been seen before, consider the sum of the two as a candidate.
- Alternatively, group numbers by digit sum and then find the two largest numbers in each group.
- The digit sum calculation runs in O(d) where d is the number of digits, negligible relative to n.
Space and Time Complexity
Time Complexity: O(n * d) ~ O(n), where d is the maximum number of digits (typically constant). Space Complexity: O(n), for storing the mapping of digit sums to numbers.
Solution
We iterate through the array and compute the digit sum for each number. We use a hash table that maps from a digit sum to the maximum number encountered with that sum. For every element, if there is already a number in the hash table with the same digit sum, we compute the sum of the current number and that maximum value, and update our result if it is greater than our current maximum sum. Then, we update the hash table with the greater of the current number or the stored maximum for that digit sum. In this way, we ensure that we have seen the best candidate for pairing with any future number with the same digit sum.