Max Sum of a Pair With Equal Sum of Digits - Problem

You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].

Return the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions. If no such pair of indices exists, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [18,43,25,61,52]
Output: 113
💡 Note: Numbers 61 and 52 both have digit sum 7 (6+1=7, 5+2=7). Their sum 61+52=113 is the maximum possible.
Example 2 — No Valid Pairs
$ Input: nums = [10,12,19,14]
Output: -1
💡 Note: Digit sums are: 1, 3, 10, 5. All different, so no pairs with equal digit sums exist.
Example 3 — Multiple Groups
$ Input: nums = [23,32,41,14,50]
Output: 91
💡 Note: Digit sum 5: 23(2+3=5), 32(3+2=5), 41(4+1=5), 14(1+4=5), 50(5+0=5). Maximum pair: 50+41=91.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Max Sum of a Pair With Equal Sum of Digits INPUT nums array (0-indexed) 18 [0] 43 [1] 25 [2] 61 [3] 52 [4] Digit Sums: 1+8=9 4+3=7 2+5=7 6+1=7 5+2=7 Groups by Digit Sum: Sum 9: [18] Sum 7: [43, 25, 61, 52] Find max pair sum in each group ALGORITHM STEPS 1 Initialize HashMap Map: digit_sum --> max_num 2 Iterate Array Calculate digit sum for each num 3 Check HashMap If sum exists, update max pair 4 Update HashMap Store max num for digit sum HashMap State (Final): 9 --> 18 7 --> 61 Best Pair Found: digit_sum = 7 nums: 52 + 61 = 113 FINAL RESULT Maximum sum pair found: 52 index [4] + 61 index [3] = 113 OK - Verified Both have digit sum = 7 5+2 = 7, 6+1 = 7 Max possible sum achieved Key Insight: Use a HashMap to track the maximum number seen for each digit sum. For each new number, if its digit sum exists in the map, calculate pair sum with stored max. This achieves O(n) time complexity by avoiding nested loops - we only need the largest number per digit sum group. TutorialsPoint - Max Sum of a Pair With Equal Sum of Digits | Hash Map Optimization
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
486 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen