In this problem, you are given an array of integers. You need to find the maximum possible sum of exactly two numbers from the array that share the exact same sum of their digits. For example, the sum of digits for 18 is , and for 36 is . If no two numbers share the same digit sum, return -1.
This is a fantastic Hash Map grouping problem. It is designed to test your ability to map derived properties (the digit sum) to the original values efficiently. Interviewers look to see if you can optimize spatial and temporal complexity. Instead of sorting groups of numbers, a strong candidate will realize they only need to track the absolute maximum number seen so far for each digit sum.
This utilizes the Hash Map / Array Grouping pattern. Since the maximum possible digit sum for a standard 32-bit integer is relatively small (e.g., ), you can use a Hash Map or a fixed-size array of size 82. As you iterate:
current_number + mapped_number is a valid pair sum. Compare it against your global maximum.max(mapped_number, current_number).Array: [18, 43, 36, 13, 7]
Map tracks digit_sum -> max_number_seen. Max_Pair_Sum = -1.
18: Digit sum 9. Map {9: 18}.43: Digit sum 7. Map {9: 18, 7: 43}.36: Digit sum 9. It's in the map! The stored number is 18. Valid pair sum: 36 + 18 = 54. Max_Pair_Sum = 54. Update map to hold max of 18 and 36. Map {9: 36, 7: 43}.13: Digit sum 4. Map {9: 36, 7: 43, 4: 13}.7: Digit sum 7. In the map! Stored number is 43. Valid pair sum: 7 + 43 = 50. Max_Pair_Sum remains 54. Update map for 7 to max(43, 7) which is 43.
The final maximum pair sum is 54.A common error is storing all numbers with the same digit sum in a list inside the Hash Map, and then sorting the list at the end to find the top two numbers. While correct, this wastes memory and introduces sorting time per group. The problem only asks for the sum of the top two numbers, so you only ever need to hold the single largest number previously seen to pair with the current one.
When an interview question asks for a "pair" based on a shared property, never build full lists of groups. Always store just the "best" historical value in your Hash Map. Processing the array in a single pass while resolving the math on the fly demonstrates highly optimal engineering habits.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Subsequence of Length K With the Largest Sum | Easy | Solve | |
| High Five | Easy | Solve | |
| Find Score of an Array After Marking All Elements | Medium | Solve | |
| Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values | Medium | Solve | |
| Reduce Array Size to The Half | Medium | Solve |