Max Sum of a Pair With Equal Sum of Digits - Problem
Imagine you're a data analyst looking for special number pairs in a dataset. You have an array of positive integers, and you need to find two different numbers that share a unique property: they have the same digit sum.
For example, the numbers 23 and 41 both have a digit sum of 5 (2+3=5, 4+1=5), making them a valid pair.
Your Goal: Find the pair with the maximum sum among all valid pairs. If no such pair exists, return -1.
Key Concepts:
- Digit Sum: Sum of all digits in a number (e.g., 123 โ 1+2+3 = 6)
- Valid Pair: Two different array elements with equal digit sums
- Objective: Maximize the sum of the pair values themselves
Input & Output
example_1.py โ Basic Case
$
Input:
[18, 43, 36, 13, 7]
โบ
Output:
54
๐ก Note:
The pairs with equal digit sums are: (18,36) with digit sum 9, and (43,13) with digit sum 7. The maximum pair sum is 18+36=54.
example_2.py โ Multiple Valid Pairs
$
Input:
[10, 12, 19, 14]
โบ
Output:
-1
๐ก Note:
No two numbers have the same digit sum: 10โ1, 12โ3, 19โ10, 14โ5. Therefore, no valid pairs exist.
example_3.py โ Large Numbers
$
Input:
[229, 398, 269, 317, 420, 464, 491, 218, 439]
โบ
Output:
953
๐ก Note:
Several pairs have equal digit sums. The pair (464, 491) both have digit sum 14 and give the maximum sum: 464+491=955. Wait, let me recalculate: 229(13), 398(20), 269(17), 317(11), 420(6), 464(14), 491(14), 218(11), 439(16). The pairs are (464,491) with sum 955, and (317,218) with sum 535. Maximum is 955.
Visualization
Tap to expand
Understanding the Visualization
1
Meet a New Suspect
Calculate their clue value (digit sum) and check your notebook
2
Check for Match
If you've seen this clue before, you found a pair! Calculate the potential reward
3
Update Notebook
Remember the most valuable suspect for this clue type
4
Track Best Reward
Keep track of the highest reward found across all pairs
Key Takeaway
๐ฏ Key Insight: By storing only the maximum value for each digit sum, we can find valid pairs in one pass while immediately calculating the best possible reward, achieving optimal O(n) time complexity!
Time & Space Complexity
Time Complexity
O(n)
Single pass through array with O(log(max_value)) digit sum calculation per element
โ Linear Growth
Space Complexity
O(k)
Hash map stores at most k unique digit sums, where k โค min(n, max_digit_sum)
โ Linear Space
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- The array contains positive integers only
- Maximum digit sum is 9ร10 = 90 for a 10-digit number
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code