Find the maximum possible sum of two distinct numbers whose digit sums are equal.
Problem
You are given an array of integers. Your task is to choose two different elements such that the sum of their decimal digits is the same for both numbers.
Among all valid pairs, return the largest possible value of a + b. If no such pair exists, return -1.
A pair is considered distinct if it uses two different array positions.
Notes
- The digit sum of a non-negative integer is the sum of all digits in its base-10 representation.
- If multiple pairs have the same digit-sum condition, only the pair with the maximum total matters.
Input Format
- An integer array
nums - Each element is treated as a base-10 integer when computing digit sum
Output Format
- Return a single integer: the maximum sum of a valid pair, or
-1if no valid pair exists
Constraints
- Use two distinct elements from the array
- A valid pair must have equal digit sums
- If no valid pair exists, return
-1
Example 1
Input
nums = [18, 43, 36, 13, 7]
Output
54
Explanation
Digit sums are: 18→9, 43→7, 36→9, 13→4, 7→7. The valid pairs are (18,36) with sum 54 and (43,7) with sum 50. The maximum is 54.
Example 2
Input
nums = [10, 12, 19, 14]
Output
-1
Explanation
Digit sums are 1, 3, 10, and 5. No two numbers share the same digit sum.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.